我创建了一个扩展 CrudRepository 的存储库, 这个存储库有一个带有@Query 符号的方法:
代码:
@Query("select itemType, count(*) as count from Item where User_id = :userId group by itemType")
List<Map<String, Long>> countItemsForUser(@Param("userId") Long userId);
我遇到的问题是这会返回对象的 ArrayList 而不是 map 列表。 我在某处读到 JPA 无法返回 Map,所以我将结果填充到 List> 中。
我不知道解决此问题或快速访问结果数据的最佳方法是什么。 我尝试过转换,但也没有成功:
for(Object item: items) {
Map<String,Long> castedItem = (HashMap<String,Long>)item;
}
最佳答案
请参阅 Hibernate 官方文档中的此示例。 Here
for (Object item:items) {
Object[] tuple = (Object[]) item;
String itemType = (String)tuple[0];
Long count = (Long) tuple[1];
}
关于java - spring-data @Query 映射结果问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10170299/