【问题标题】:How to return map with multiple sum in jpql jpa?如何在jpql jpa中返回具有多个总和的地图?
【发布时间】:2021-02-10 14:47:30
【问题描述】:

这是我的查询

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

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

【问题讨论】:

标签: java spring-boot jpa jpql


【解决方案1】:

解决方案 1: 使用 totalDay 和 totalMonth 创建一个模型,并创建一个全参数构造函数。

public class UserDataModel {
    Long totalDay;
    Long totalMonth;

    public UserDataModel(Long totalDay, Long totalMonth) {
        this.totalDay = totalDay;
        this.totalMonth = totalMonth;
    }
    
    //getter and setter
}

像这样改变你的查询

@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);

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

public interface UserDataModelV2 {
    Long getTotalDay();
    Long getTotalMonth();
}

像这样改变你的方法。

    @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);

如果要返回 HashMap 而不是 POJO,可以使用 hashMap 扩展 UserDataModel,并在构造函数中将数据放入映射中。

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
}

或者您可以将解决方案 2 中的接口替换为 Map

@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);

【讨论】:

  • 是否可以返回 Map&lt;String, Integer&gt; 而不是 List&lt;UserDataModelV2&gt; ?其中 map 键是 totalDay,值是总和。我不想创建对象
  • 您可以使用 HashMap 扩展 UserDataModel,并在构造函数中填充地图。
  • 是的,你可以使用 map 代替 Userdatamodelv2,我已经更新了 ans。
  • 我想要的只是List&lt;Map&lt;Stirng, Object&gt;&gt; 谢谢
【解决方案2】:

您应该将 Integer 替换为 Object[]

Object[] getRecod(Long id);

因为SUM(d.day) as totalDay, SUM(d.month) as totalMonth在数组中返回两个长值

【讨论】:

  • 是有序数组吗?我的意思是我总是在数组 [0] 处得到第一个总和,在数组 [1] 处得到第二个总和吗?如果没有排序,那么它将随机运行
  • 是的,有序数组,数组[0]处的总日和数组[1]处的总月
猜你喜欢
  • 2013-08-23
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 2012-05-06
  • 1970-01-01
  • 2020-06-18
相关资源
最近更新 更多