Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve single field rather than whole pojo in hibernate

Tags:

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 thing?

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 ?

like image 892
Sanju Avatar asked Jun 03 '11 06:06

Sanju


2 Answers

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();
like image 102
Stevi Deter Avatar answered Nov 04 '22 02:11

Stevi Deter


You need property projection http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html#querycriteria-projection

like image 25
Sly Avatar answered Nov 04 '22 00:11

Sly