如何解决如何在jpql jpa中返回具有多个和的映射?
这是我的查询
select SUM(d.day) as totalDay,SUM(d.month) as totalMonth from record d where d.userId = ?1
Integer getRecod(Long id);
解决方法
您应将Integer
替换为Object[]
:
Object[] getRecod(Long id);
因为SUM(d.day) as totalDay,SUM(d.month) as totalMonth
返回数组中的两个long值
解决方案1: 使用totalDay和totalMonth创建一个模型,并创建一个所有args构造函数。
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
}
或者您可以用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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。