想象一下,我们有一个实体:
@Entity
public class Person implements Serializable {
@Id
private String name;
private Long age;
private Boolean isMad;
...
}
一个包含自定义查询的简单(和不必要)示例的存储库:
@Repository
public interface PersonRepository extends PagingAndSortingRepository<Info, String> {
@Query("select p.isMad, count(*) from Person p group by p.isMad")
List<Object> aggregateByMadness();
}
现在解析这个List我们需要做这样的事情:
for (Object element : list) {
Object[] result = (Object[]) element;
Boolean isMad = (Boolean) result[0];
Long count = (Long) result[1];
}
这是一种痛苦,我们可以将查询结果直接转换为POJO列表吗?
答案 0 :(得分:2)
是的,您可以使用JPQL construction expression:
package com.foo;
public class Madness {
public Madness(boolean isMad, Number count) { /* ...*/ }
}
在您的存储库中:
@Query("select new com.foo.Madness(p.isMad, count(*)) from Person p group by p.isMad")
List<Madness> aggregateByMadness();