如何在jpql jpa中返回具有多个总和的映射?

mah*_*sif 2 java jpa jpql spring-boot

这是我的查询

select SUM(d.day) as totalDay, SUM(d.month) as totalMonth from record d where d.userId = ?1
Integer getRecod(Long id);
Run Code Online (Sandbox Code Playgroud)

由于查询未返回整数,因此发生错误。我应该用整数替换什么?

Sha*_*rup 5

解决方案 1:创建一个包含totalDay 和totalMonth 的模型,并创建一个all args 构造函数。

public class UserDataModel {
    Long totalDay;
    Long totalMonth;

    public UserDataModel(Long totalDay, Long totalMonth) {
        this.totalDay = totalDay;
        this.totalMonth = totalMonth;
    }
    
    //getter and setter
}
Run Code Online (Sandbox Code Playgroud)

更改您的查询,例如

@Query(value = "select 
new com.package.UserDataModel(SUM(d.day) as totalDay, SUM(d.month) as totalMonth) 
from Record d where d.userId = ?1 ")
    UserDataModel getRecord(Long id);
Run Code Online (Sandbox Code Playgroud)

解决方案2:使用弹簧投影。创建一个像这样的界面。确保遵循正确的 camcelCase。

public interface UserDataModelV2 {
    Long getTotalDay();
    Long getTotalMonth();
}
Run Code Online (Sandbox Code Playgroud)

像这样改变你的方法。

    @Query(value = "select " +
            " SUM(d.day) as totalDay, SUM(d.month) as totalMonth " +
            "from Record d where d.userId = ?1")
    List<UserDataModelV2> getRecord(Long id);
Run Code Online (Sandbox Code Playgroud)

如果你想返回一个HashMap而不是POJO,你可以用hashMap扩展UserDataModel,并在构造函数中将数据放入map中。

public class UserDataModel extends HashMap<String, Object>{
    Long totalDay;
    Long totalMonth;

    public UserDataModel(Long totalDay, Long totalMonth) {
        this.totalDay = totalDay;
        this.totalMonth = totalMonth;
        put("totalDay",totalDay); 
        put("totalMonth",totalMonth); 
    }
    
    //getter and setter
}
Run Code Online (Sandbox Code Playgroud)

或者您可以将解决方案 2 中的 Interface 替换为 Map<Stirng, Object>。

@Query(value = "select " +
            " SUM(d.day) as totalDay, SUM(d.month) as totalMonth " +
            "from Record d where d.userId = ?1")
    List<Map<Stirng, Object>> getRecord(Long id);
Run Code Online (Sandbox Code Playgroud)