Jpa Specification分组查询如何排除id字段?
JPA Specification分组查询报错解决方案
问题原因
你遇到的报错是因为:你的Specification泛型指定的是AggregatedData实体类,JPA默认会尝试将查询结果映射到该实体,但实体包含id字段,而你的分组查询既没把id加入GROUP BY,也没对它使用聚合函数。PostgreSQL的严格SQL模式要求SELECT中的非聚合列必须出现在GROUP BY里,所以触发了这个错误。
你不需要把id加到GROUP BY里,以下两种方案可以解决问题:
方案1:用DTO接收聚合结果
既然你要的是统计聚合数据,不需要完整的AggregatedData实体,可以定义一个专门的DTO类来接收查询结果:
1. 定义DTO类
public class AggregatedStatsDTO { private String file; private String bok; private String taskNumber; private String documentType; private Long to8PagesSum; private Long from9To20PagesSum; // 注意:构造方法参数顺序必须和查询中multiselect的字段顺序完全一致 public AggregatedStatsDTO(String file, String bok, String taskNumber, String documentType, Long to8PagesSum, Long from9To20PagesSum) { this.file = file; this.bok = bok; this.taskNumber = taskNumber; this.documentType = documentType; this.to8PagesSum = to8PagesSum; this.from9To20PagesSum = from9To20PagesSum; } // 生成对应的getter方法 }
2. 修改Specification代码
把泛型改成DTO类型,用cb.construct()指定构造DTO:
Specification<AggregatedStatsDTO> spec = (root, criteriaQuery, cb) -> { Predicate conditions = cb.and( cb.between(root.get("sendDate"), beginDate, endDate), cb.equal(root.get("taskNumber"), taskNum) ); criteriaQuery.select(cb.construct(AggregatedStatsDTO.class, root.get("file"), root.get("bok"), root.get("taskNumber"), root.get("documentType"), cb.sum(root.get("to8Pages")), cb.sum(root.get("from9To20Pages")) )) .where(conditions) .groupBy( root.get("file"), root.get("bok"), root.get("taskNumber"), root.get("documentType") ) .orderBy(cb.desc(root.get("taskNumber")), cb.desc(root.get("bokNumber"))); return null; };
3. 修改Repository方法
让Repository返回DTO类型:
List<AggregatedStatsDTO> findAll(Specification<AggregatedStatsDTO> spec);
方案2:使用Spring Data JPA接口投影
如果不想创建DTO,可以用接口投影来接收结果:
1. 定义投影接口
接口中的方法名要和查询字段(或别名)对应:
public interface AggregatedStatsProjection { String getFile(); String getBok(); String getTaskNumber(); String getDocumentType(); // 这里的方法名要和聚合函数的别名一致 @Value("#{target.to8PagesSum}") Long getTo8PagesSum(); @Value("#{target.from9To20PagesSum}") Long getFrom9To20PagesSum(); }
2. 修改Specification代码
给聚合函数添加别名,对应投影接口的方法:
Specification<AggregatedStatsProjection> spec = (root, criteriaQuery, cb) -> { Predicate conditions = cb.and( cb.between(root.get("sendDate"), beginDate, endDate), cb.equal(root.get("taskNumber"), taskNum) ); criteriaQuery.multiselect( root.get("file").alias("file"), root.get("bok").alias("bok"), root.get("taskNumber").alias("taskNumber"), root.get("documentType").alias("documentType"), cb.sum(root.get("to8Pages")).alias("to8PagesSum"), cb.sum(root.get("from9To20Pages")).alias("from9To20PagesSum") ) .where(conditions) .groupBy( root.get("file"), root.get("bok"), root.get("taskNumber"), root.get("documentType") ) .orderBy(cb.desc(root.get("taskNumber")), cb.desc(root.get("bokNumber"))); return null; };
3. 修改Repository方法
让Repository返回投影接口类型:
List<AggregatedStatsProjection> findAll(Specification<AggregatedStatsProjection> spec);
内容的提问来源于stack exchange,提问作者danny
相关产品推荐
相关产品推荐

