The Hibernate Criteria Projection contains all the projections instances. You can add many projection in to it by calling setProjection() method.
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("rollNo"));
projectionList.add(Projections.property("name"));
projectionList.add(Projections.property("course"));
criteria.setProjection(projectionList);
Please consider the given example on projection
CriteriaProjection.java
package net.roseindia.main;
import java.util.Iterator;
import java.util.List;
import net.roseindia.bean.Student;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
public class CriteriaProjection {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Student.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("rollNo"));
projectionList.add(Projections.property("name"));
projectionList.add(Projections.property("course"));
criteria.setProjection(projectionList);
List list = criteria.list();
Iterator iterator = list.iterator();
System.out.println("\n");
System.out.print("\tRoll No");
System.out.print("\t");
System.out.print("\tName");
System.out.print("\t");
System.out.print("\tCourse");
System.out.print("\t");
System.out.println();
while (iterator.hasNext()) {
System.out.println("");
Object[] objects = (Object[]) iterator.next();
for (int i = 0; i < objects.length; i++) {
System.out.print("|\t" + objects[i] + "\t");
}
}
}
}
| Hibernate: select this_.roll_no as y0_, this_.name
as y1_, this_.course as y2_ from student this_ Roll No Name Course | 1 | Ramesh | MCA | 2 | Raman | B.Tec | 3 | Aman | BCA | 4 | Raman | MCA | 5 | Vikash | MBA | 6 | Ramesh | DCA | 7 | Bharat | MCA |