Hibernate one-to-one mapping using Annotations

In this article, we will create one-to-one mapping between “phone” and “phone_detail” tables. Here, one phone can have one phone_detail record. To create the relationships, lets first create the tables.   Creating tables We have set the “hibernate.hbm2ddl.auto” parameter to “create” which should create the tables when the program is run. But you can also […]

Hibernate Annotations

Hibernate allows using XML based mapping files to map the POJO elements to database. However, we can also use annotations for the same as they are easy to use and make the development process faster. This article mentions the basic and necessary annotations for creating entity classes. Hibernate uses and supports the JPA 2 persistence […]

Hibernate Projections

Projections The Projection class is used in Hibernate to query specific elements. It also provides some build-in aggregate functions like sum, max, min etc. The Projections class provides several static factory methods for obtaining Projection instances. After you get a Projection object, add it to your Criteria object with the setProjection() method.   Selecting only […]

Transforming database query result to Map using Transformers and Criteria api

We can use Hibernate Criteria to convert records returned by Hibernate to a Map. For this, we can set the ResultTransformers in following manner : Criteria criteria = session.createCriteria(Employee.class); criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); This converts every record returned to a Map. If we get the records using criteria.list() and print, they will look like this : [{this=Employee{id = […]

Sorting query results using Hibernate Criteria api

We can use Hibernate Criteria to sort records by a column name in ascending or descending order Example : Sorting records using Criteria api In following example, we will sort Employee records in ascending order of name. package com.topjavatutorial; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Order; public class HibernateDemo { […]