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.
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.
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.
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 .
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.
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?
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]; .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With