I am a little confused about Hibernate\'s projections and criteria. When to use projections and when to use criteria?
Projections are used to execute aggregate operations and to get single column query,with Restrictions we can access a ROW but with PROJECTIONS we can access whole COLUMN
EX -
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
Session session = factory.getCurrentSession();
try {
session.beginTransaction();
Criteria c = session.createCriteria(Student.class);
Projection p = Projections.property("lastName");
List students = c.setProjection(p).list();
for(String s:students)
System.out.println(s);
session.getTransaction().commit();
session.close();
} finally {
factory.close();
}
}
In the above example i used projection call to ADD a projection property "name" to the criteria. It returns winchester winchester winchester winchester , which is the lastName COLUMN in the table.
Output =
Hibernate: select this_.last_name as y0_ from student this_ winchester winchester winchester winchester
Note - We can add only one projection, if we add more than 1 projection previous one will be overridden. if you want to add more than one projection you will nedd ProjectionList class
Orignal Table -