最近帮老同事解决一个问题,场景是这样的,查询条件比较多,也就是我们说的联合查询,比如下面的,时间可以选不同的,状态和来源也可以选不同,而且可选可不选
如果这个时候写sql,是不是要各种条件判断,各种纠结,各种难写,各种sql,这个时候大家一般都想到了springdata的jpa貌似很好用,可以直接拼接sql,但是怎么拼接呢,又怎么支持非表字段的展示呢,比如表中一个字段 aaa 好展示,但是查总和sum(aaa) ,怎么把这个作为一个字段展示呢。不罗嗦了,直接上代码,以下语句对应的sql大概是,select count(***) from *** where *** group by ***
private List<Tuple> getCountByStatusOrSource(Integer status, Integer source, Integer userId, String startTime, String endTime, Integer timeSlot, String type) throws Exception {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
Date sTime = new Date(), eTime = new Date();
CriteriaQuery<Tuple> query = cb.createTupleQuery();
Root<AAA> root = query.from(AAA.class);//AAA是对应数据库的类名,替换成自己的
Path<Integer> statusPath = root.get("status");
Path<String> statusNamePath = root.get("status").get("name");
Path<Integer> sourcePath = root.get("source");
Path<Date> operatorPath = root.get("operator");
List<Predicate> predicateList = new ArrayList<>();
if (source != null) {
predicateList.add(
cb.equal(sourcePath, source)
);
}
if (userId != null) {
predicateList.add(
cb.equal(operatorPath, userId)
);
}
Map timeMap = getChangedTime(startTime, endTime, timeSlot);//获取时间的方法,具体代码我就不沾了,自己写个就行了
sTime = (Date) timeMap.get("sTime");
eTime = (Date) timeMap.get("eTime");
Expression<Date> startDateExpression = cb.literal(sTime);
Expression<Date> endDateExpression = cb.literal(eTime);
predicateList.add(
cb.between(updateTimePath, startDateExpression, endDateExpression)
);
Predicate[] predicates = new Predicate[predicateList.size()];
predicates = predicateList.toArray(predicates);
query.where(predicates);//where条件加上
if ("status".equals(type)) {
query.select(cb.tuple(statusPath, cb.count(root)));
query.groupBy(statusPath);
}
//query.multiselect(statusPath, cb.count(root));//
TypedQuery<Tuple> q = entityManager.createQuery(query);
List<Tuple> result = q.getResultList();
return result;
}
这个sql,我们分别查到了两个值 status 和数量,那么怎么获取呢
循环一下那个获取的list
Tuple tuple = list.get(i);(long)tuple.get(0)获取的是数量(Integer)tuple.get(1)获取的是状态id
到这是否全部清晰了呢,有问题的可以给我留言,这个例子也适用sum,max等其他聚合函数
本文介绍了如何在Spring Data JPA中使用聚合函数进行联合查询,通过示例展示了如何处理复杂查询条件并计算自定义字段的总和。利用CriteriaBuilder进行条件拼接,实现灵活的SQL构建,并将聚合结果如SUM、MAX等作为新的字段展示。通过循环获取的查询结果列表,可以轻松获取所需信息。
822





