In JPQL, I can retrieve entities by :
query = entityManager.createQuery("select c from Category c");
List<Category> categories = query.getResultList();
But, if I wish to retrieve the id and name fields (only) of the Category entity, I need something like the ResultSet
object, through which I can say : rs.getString("name")
and rs.getString("id")
. How to do this through JPQL
, without retrieving the entire entity ?
Basically, for a how to retrieve information from a query like : select c.id,c.name from Category c
?
It is not the use of the
.list()
function itself which makes the result aList<Object[]>
. It is the specification of fields (c.id, c.name
) in the HQL query. If your query isThen
query.list()
will return aList<Category>
object.In HQL you can use list() function to get a list of Object[] array that contains result rows:
in returned array 1-st element will be id, second - name.
If you want to use hibernate's Criteria API, you should use Projections.
With JPA it will work the same way:
You can also directly map to the class