tags:

views:

45

answers:

2

What is the simplest hibernate criteria query equivalent of

SELECT name FROM people WHERE id='3'

is it :

criteria.add(Expression.eq("id", 3));

and how can I retrieve it to String variable the value of name field, the IDs are unique

+4  A: 

If you are querying by "id", why would you set up your Hibernate criteria to use "name"? If "id" is mapped as your primary key and you want to load the object directly, use the Get method off of Session.

Example:

People thePerson = (People) session.get(People.class, new Integer(1));

You might also want to try reading this.

Lance Harper
@Lance Harper I meant ID I fixed it, can you show me example?
c0mrade
Edited. Assuming your class is named "People" and your session variable is named "session", that should load the one person with the id of 1.
Lance Harper
+1  A: 

I think you just want to project name and not get the full entity.

Criteria crit = session.createCriteria(People.class)
  .add(Restrictions.eq("id", 3);
ProjectionList projectList = Projections.projectionList();
projectList.add(Projections.property("name"));
crit.setProjection(projectList);

(String) crit.uniqueResult();

I would just go with using session.get(..) in this case as well since you are only retrieving 1 person and don't need to go through the trouble of specifying anything.

Arthur Thomas