Return a subset of a JPA entity as a array of maps

2020-07-11 08:05发布

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?

1条回答
乱世女痞
2楼-- · 2020-07-11 08:40

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.

查看更多
登录 后发表回答