Retrieve single field rather than whole pojo in hibernate
I have some query regarding hibernate,
Table : Employee_Master
Id Number Name Varchar Salary long
POJO: EmployeeMaster.java
public class EmployeeMaster {
private int id ;
private String name;
private long salary;
//... all field s getter/ setter methods
}
Now I want to get only name from such id.
SQL query like like:
select name from employee_master where id = 10;
But how can we achieve in hibernate the above same t开发者_StackOverflow社区hing?
session.createQuery("from EmployeeMaster empMaster where empMaster.id = 10");
This solution I know but it will return whole pojo list. But I want only that field name so what should I do ?
In HQL, you can simply ask for the one field:
String employeeName = session.createQuery("select empMaster.name from EmployeeMaster empMaster where empMaster.id = :id").setInteger("id",10).uniqueResult();
You need property projection http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html#querycriteria-projection
This is working for me
String orderNo = (String) getCurrentSession().createQuery("select orderNumber from Asset where id = :id").setParameter("id", assetId).uniqueResult();
setInteger doesn't work for me then I used setParameter.
// to retrieve a single row or record
String hqlSelectRow ="from Employee where employeeId =:empId";
Query query1 = session.createQuery(hqlSelectRow);
Employee emp = (Employee) query1.setParameter("empId",111).uniqueResult();
System.out.println("employee id : "+ emp.getEmployeeId() );
System.out.println("employee name : "+ emp.getEmployeeName() );
System.out.println("employee salary : "+ emp.getEmployeeSalary());
You tagged nhibernate, but your reference to pojo's make me assume you're writing in Java. Are you using JPA? If so, consider using a native query...
EntityManager em ....
Query q = em.createNativeQuery("select e.name from employee_master e where e.id = ?");
q.setParamter(1, <employee id>);
String name = (String) q.getSingleResult();
Use the Hibernate Projection, here an example where i retrieve only unique idCsvAccount of my table :
Criteria criteria = ...;
criteria.add(Restrictions.eq("idUser", idUser));
return (Long) criteria.setProjection(Projections.property("idCsvAccount")).uniqueResult();
Here an example for multiple results :
Criteria criteria = ...;
criteria.add(Restrictions.eq("idUser", idUser));
return ((List<Long>) criteria.setProjection(Projections.property("idCsvAccount")).list());
精彩评论