emt14
emt14

Reputation: 4896

Can Hibernate Custom query return a Map instead of a List?

Is it possible to return a map instead of a List from a custom JPA Query?

I know if is possible from the Entities themselves. In my case I have a custom query which returns some stats across different tables for a range of dates.

Ideally I would like the returned map to have the date as key and the stat as value.

Upvotes: 5

Views: 4656

Answers (1)

JB Nizet
JB Nizet

Reputation: 692023

You'll just have to create and populate the map by yourself:

List<Object[]> rows = query.list();
Map<Date, Integer> statsPerDate = new HashMap<Date, Integer>(rows.size());
for (Object[] row : rows) {
    Date date = (Date) row[0];
    Integer stat = (Integer) row[1];
    statsPerDate.put(date, stat);
}

Upvotes: 5

Related Questions