
How to use criteria to return only one element of an object instead the entire object?

You can use projection to select one element of object. Here is an example to retrieve only name of employee.
Example :
package net.roseindia.main;
import java.util.List;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
public class CriteriaById{
public static void main(String []args){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
Session session=sessionFactory.openSession();
Criteria criteria=session.createCriteria(Employee.class).setProjection(Projections.property("name"));
List<String> employeeList = (List<String>)criteria.list();
for(String employee: employeeList){
System.out.println(employee);
}
}
}
Output :
Hibernate: select this_.name as y0_ from employee this_ Mandy Som Mandy Roxi
If you want value under condition,you can add restriction.
Criteria criteria=session.createCriteria(Employee.class).add(Restrictions.eq("id",2)).setProjection(Projections.property("name"));
Output:
Hibernate: select this_.name as y0_ from employee this_ where this_.emp_id=? Som