Projection in Hibernate

What is Projection


Projection is an Interface given in “org.hibernate.criterion” package

You can also use Projections to specify distinct clauses and aggregate functions like max, sum, AVG etc.

When to Use Projection


Your table containing lots of data. If you want to select or project some data then we use projection.
Suppose emp table containing name, sal, job, location etc
And now if you want project employee name then we use projection.

Hibenrate program to get Max ID using Projection

Projection.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.spy.operation;
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.Projections;
import org.hibernate.criterion.Restrictions;
public class Projection
{
	public static void main(String[] args)
	{
			SessionFactory sessionfactory=new Configuration().configure().buildSessionFactory();
			Session session=sessionfactory.openSession();
			session.beginTransaction();
 
			//projection get max id
			Criteria criteria= session.createCriteria(Userdata.class)
			.setProjection(Projections.max("id"));
 
			/*
 
			//Projection to get number of record
			Criteria criteria2= session.createCriteria(Userdata.class)
			.setProjection(Projections.count("user"));
 
			*/
 
 
			List user=criteria.list();
			session.getTransaction().commit();
			session.close();
 
			for (Object userdata : user)
			{
			  System.out.println(userdata.toString());
			}
 
	}
}

Output:

1
2
3
 
Hibernate: select count(this_.user) as y0_ from Userdata this_
9

Leave a Reply

Your email address will not be published. Required fields are marked *