I am a little confused about Hibernate\'s projections and criteria. When to use projections and when to use criteria?
Projection is an Interface given in “org.hibernate.criterion” package, Projections is an class given in same package, actually Projection is an interface, and Projections is an 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 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
Criteria crit = session.createCriteria(Products.class);
crit.setProjection(Projections.proparty("proName"));
List l=crit.list();
Iterator it=l.iterator();
while(it.hasNext())
{
String s = (String)it.next();
// ---- print -----
}
If we add multiple projections to criteria then the last projection added will be considered to execute see…
Criteria crit = session.createCriteria(Products.class);
Projection p1 = Projection.property("proName");
Projection p2 = Projection.property("price");
crit.setProjection(p1):
crit.setProjection(p2):
List l=crit.list();