user1191027
user1191027

Reputation:

How do you select a column using Hibernate?

I would like to select a single column instead of a whole object, using Hibernate. So far I have this:

 List<String> firstname = null;

 firstname = getSession().createCriteria(People.class).list();

My problem is that the above code returns the whole People table as an object instead of just "firstname". I'm not sure how to specify to only return "firstname" instead of the whole object.

Upvotes: 38

Views: 66490

Answers (3)

DDshah
DDshah

Reputation: 41

You can use ProjectionList if you want condition base projection e.g

  ProjectionList prjection = Projections.projectionList();
if(abc){
    prjection.add(Projections.property("firstname"));
}
else if(xyz){
    prjection.add(Projections.property("lastname"));
}

    ........

    criteria.setProjection(prjection);

Upvotes: 2

Thai Tran
Thai Tran

Reputation: 9935

If you need to query 2 or more columns and get the values from the query, this is the way to do it:

....
crit.setProjection(Projections.property("firstname"));
crit.setProjection(Projections.property("lastname"));

List result = crit.list();

...

for (Iterator it = result.iterator(); it.hasNext(); ) {
    Object[] myResult = (Object[]) it.next();
    String firstname = (String) myResult[0];
    String lastname = (String) myResult[1];

    ....
}

Upvotes: 8

rizzz86
rizzz86

Reputation: 3990

You can set the Projection for this like:

.setProjection(Projections.property("firstname"))

With this you can only get the firstname in return.

I have found another link on stack with the same scenario. Hope this will also help How to use hibernate criteria to return only one element of an object instead the entire object?

Upvotes: 47

Related Questions