Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 578
ThreaT Avatar asked May 18 '12 12:05

ThreaT


People also ask

How can I get specific column in Hibernate?

You can use multiselect function for this. This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

How do I select a single column in HQL?

In HQL you can use list() function to get a list of Object[] array that contains result rows: Query query = session. createQuery("select e. uid from Empdata e"); List<Object[]> rows = query.

How can I get single record in hibernate?

Use the uniqueResult() API method of Criteria to get the single instance that matches the query. Use again getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction .

What is Criteria query in hibernate with example?

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.


2 Answers

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?

like image 149
rizzz86 Avatar answered Sep 21 '22 06:09

rizzz86


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];      .... } 
like image 29
Thai Tran Avatar answered Sep 19 '22 06:09

Thai Tran