JPA聚合函数(适用于联合查询)
来源:互联网 发布:联通2g网络制式 编辑:程序博客网 时间:2024/05/16 14:46
最近帮老同事解决一个问题,场景是这样的,查询条件比较多,也就是我们说的联合查询,比如下面的,时间可以选不同的,状态和来源也可以选不同,而且可选可不选
如果这个时候写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等其他聚合函数
1 0
- JPA聚合函数(适用于联合查询)
- JPA联合查询问题解决
- 多表联合查询中使用聚合函数
- mysql(二):使用聚合函数查询
- mysql(二):使用聚合函数查询
- 使用聚合函数查询
- 查询—聚合函数
- 聚合函数查询
- SQL聚合函数查询
- 聚合函数查询
- 使用聚合函数查询
- JPA联合查询方法二(应用托管的(application-managed)EntityManager对象 )
- 聚合函数查询、连接查询、子查询
- 聚合函数查询的SQL
- 查询语句之聚合函数
- hql中聚合函数查询
- 表查询与聚合函数
- mysql分组查询聚合函数
- Dreamwear使用
- 文本和字体:文本修饰
- spring定时器表达式
- spring源码分析
- C++面向对象高级开发_极客班_第一节课笔记_section3
- JPA聚合函数(适用于联合查询)
- 用ul、li标签创建css横向导航菜单示例
- 日期转换工具以及常用的字符,产生随机数,将java流中的编码转换为utf-8----java
- APK分包加载
- android ViewPager滑动事件
- 设置导航栏右边返回按钮文字
- 从”JAVA“而终 27:Ajax讲解
- 在串口通信开发中实现自动查找串口端口的方法
- 几种损失函数(Loss Function)