Projections Introduction
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.