JPA聚合函数(适用于联合查询)

最近帮老同事解决一个问题,场景是这样的,查询条件比较多,也就是我们说的联合查询,比如下面的,时间可以选不同的,状态和来源也可以选不同,而且可选可不选

如果这个时候写sql,是不是要各种条件判断,各种纠结,各种难写,各种sql,这个时候大家一般都想到了springdata的jpa貌似很好用,可以直接拼接sql,但是怎么拼接呢,又怎么支持非表字段的展示呢,比如表中一个字段 aaa 好展示,但是查总和sum(aaa) ,怎么把这个作为一个字段展示呢。不罗嗦了,直接上代码,以下语句对应的sql大概是,select count(***) from *** where *** group by ***

private List 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 query = cb.createTupleQuery();
        Root root = query.from(AAA.class);//AAA是对应数据库的类名,替换成自己的
        Path statusPath = root.get("status");
        Path statusNamePath = root.get("status").get("name");
        Path sourcePath = root.get("source");
        Path operatorPath = root.get("operator");

        List 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 startDateExpression = cb.literal(sTime);
            Expression 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 q = entityManager.createQuery(query);
        List result = q.getResultList();
        return result;
    }

这个sql,我们分别查到了两个值 status 和数量,那么怎么获取呢

循环一下那个获取的list

Tuple tuple = list.get(i);
(long)tuple.get(0)获取的是数量
(Integer)tuple.get(1)获取的是状态id


到这是否全部清晰了呢,有问题的可以给我留言,这个例子也适用sum,max等其他聚合函数



你可能感兴趣的:(java,web)