Friday, December 11, 2015

How to use projection in Hibernate ?

The projections concept is introduced in hibernate
3.0 and mainly we can do the following two operations using the projection
We can load partial object from the database
We can find the Result of Aggregate functions
Projection is an Interface given in “org.hibernate.criterion” package, Projections is a class
given in same package, actually Projection is an interface, and Projections is a class and is a
factory for producing projection objects.
In Projections class, we have all static methods and each method of this class returns
Projection interface object.
If we want to add a Projection object to Criteria then we need to call a
method setProjection()
Remember : while adding projection object to criteria, it is possible to add one object at a
time. It means if we add 2nd projection object then this 2nd one will overrides the first one
(first one wont be work), so at a time we can have only one projection object to criteria
object.
Using criteria, if we want to load partial object from the database, then we need to create a
projection object for property that is to be loaded from the database

How to use?
Criteria criteria = session.createCriteria(Entity.class);
criteria.setProjection(Projections.property("name"));
List list = criteria.list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
             String s = (String) iterator.next();
             // ---- further code -----
}

If we add multiple projections to criteria then the last projection added will be considered
to execute

Criteria criteria = session.createCriteria(Entity.class);
Projection p1 = Projection.property("id");
Projection p2 = Projection.property("name");
criteria.setProjection(p1):
criteria.setProjection(p2):
List list=crit.list();

Here collectiions list, is going to contain the name in the form of String objects, but Entity id are
over ridden, second projection over rides the first one, i mean p2 only will works p1 will not works,
actually there is a way to add multiple projections to criteria to select more than one column value.

SessionFactory sessionFactoryObj = configurationObj.buildSessionFactory();
Session sessionObj = sessionFactoryObj.openSession();

Criteria criteriaObj = sessionObj.createCriteria(Entity.class);
criteriaObj.addOrder(Order.desc("id"));

ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("id"));
projList.add(Projections.property("category"));
criteriaObj.setProjection(projList);

List entityList = criteriaObj.list();
Iterator iteratorObj = entityList.iterator();
System.out.println("ID \t CATEGORY ");

while(iteratorObj.hasNext()){
       Object data[] = (Object[])iteratorObj.next();
      System.out.println(data[0]+" \t "+data[1]);
}

No comments:

Post a Comment