First of all, let's understand what projection is. It is a class provided by hibernate that is used to select a particular field while querying. Apart from that, we can use some built-in aggregation functions provided by hibernate.
Here, we will only consider a basic projection. Now, the scenario is that we need only the id
and firstName
fields from the employee
table to set them in projection.
If we have only one field to select, we can directly use the following code:
setProjection(Projections object);
However, if we need more than one column in the result, we need to use the ProjectionList
class, as follows:
setProjection(ProjectionList object);
When we use ProjectionList
, hibernate returns List<Object>
in the result. So, it's better to use ALIAS_TO_ENTITY_MAP
for the ease of access of fields; however, it depends on the actual requirement.
Here, we will take a look at two scenarios that show how to select single and multiple fields while querying with hibernate.
We want to select only one field using.
The equivalent SQL query to select only the id
column from the employee
table is as follows:
SELECT id FROM employee.
Let's take a look at how to achieve such a condition in hibernate:
Enter the following code:
Criteria criteria = session.createCriteria(Employee.class); criteria.setProjection(Projections.property("id")); System.out.println(criteria.list());
We want to select multiple fields.
The equivalent SQL query to select multiple id
and firstName
columns from the employee
table in hibernate is as follows:
SELECT id, firstName FROM employee.
Let's take a look at how to achieve such a condition in hibernate:
Enter the following code:
Criteria criteria = session.createCriteria(Employee.class); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.alias(Projections.property("id"), "empId")); projectionList.add(Projections.alias(Projections.property("firstName"), "empFirstName")); criteria.setProjection(projectionList); criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List list = criteria.list(); System.out.println(list);
The output will be as follows:
[{empId=1, empFirstName=yogesh}, {empId=2, empFirstName=aarush}, {empId=3, empFirstName=varsha}, {empId=4, empFirstName=vishal}]
From the output, we can easily determine that projection is applied and only the two required columns are returned.
Now you will easily understand how projection works.