6

I've created a Repository that extends CrudRepository, this repository has a method with an @Query notation:

Code:

@Query("select itemType, count(*) as count from Item where  User_id = :userId group by itemType")
List<Map<String, Long>> countItemsForUser(@Param("userId") Long userId);

The issue I'm having is that this return a ArrayList of Object(s) and not a List of Map. I've read somewhere that JPA can't return a Map so that's why I stuff the result in a List>.

I don't know what's the best way to work around this issue or to quickly access the result data. I've tried casting but that didn't work out either:

for(Object item: items) {
    Map<String,Long> castedItem = (HashMap<String,Long>)item;
}
DataNucleus
  • 15,497
  • 3
  • 32
  • 37
Jonas Geiregat
  • 5,214
  • 4
  • 41
  • 60

2 Answers2

4

See this example in official documentation of Hibernate.Here

 for (Object item:items) {
   Object[] tuple = (Object[]) item;
    String itemType = (String)tuple[0];
    Long count = (Long) tuple[1];

  }
Phani
  • 5,319
  • 6
  • 35
  • 43
0

Most simple way is to use interface. To let Spring wire query alias to the interface getter. Example can be found here: https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions also there is @SqlResultSetMapping. See: JPA- Joining two tables in non-entity class