1

如果我想按JpaRepository类返回多个字段怎么办:

@Query("select u.age, count(u.id) from User u group by u.age")
List<Map<String, Object>> getAgeHistogram();

而不是一个?不可能吗?根据JPQL BNF,这是不可能的:

select_expression ::=
    single_valued_path_expression |
    aggregate_expression |
    identification_variable |
    OBJECT(identification_variable) |
    constructor_expression

除非您使用constructor_expressionDTO(我不测试此代码):

@Query("select new org.dao.dto.AgeHistogram(u.age, count(u.id)) from User u"
        +" group by u.age")
org.dao.dto.AgeHistogram getAgeHistogram();

更新这个答案展示了一些技术:How to get many object types returned in Hibernate Is it possible in JPA?

4

0 回答 0