Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a subset of a JPA entity as a array of maps from a JPQL query?

In JPQL it is possible to ask for a subset of an entity using a constructor expression such as

SELECT NEW example.EmployeeDetails(e.name, e.salary, e.department.name) FROM Employee e

which returns a list of objects of type EmployeeDetails

or using a projection select such as

SELECT e.name, e.salary FROM Employee e

which returns an Object[] result where result[0] is e.name and result[1] is e.salary

is there a way to get JPA to return a Map which contains a subset of the entity for example is there a JPQL query that can return List<Map<String,Object>> result such that result.get(0).get("e.name") return e.name and result.get(0).get('e.salary') return e.salary

If JPQL can't do it does can HQL do it?

like image 796
ams Avatar asked Aug 22 '12 15:08

ams


1 Answers

JPA provides limited amount of return types for compound selection: array, tuple and construct, while Hibernate provides much more return types for select clause, which includes Map.

SELECT NEW map(e.name, e.salary, e.department.name) FROM Employee e

This HQL query returns a Map from aliases to selected values.

like image 200
JMelnik Avatar answered Sep 28 '22 00:09

JMelnik