解决方案 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);