jpa复杂查询groupby失败的原因以及替代方法-20190824

问题

1  jpa specification 复杂查询,拼接group by 时,分页会触发select  count (*),导致指定select * from table group by 字段,造成语法错误;

2  对于oracle number 类型,虽然JavaBean中定义啦 intege,但是单独查会造成无法转型bigdecimal错误

解决方法

1   用hibernate的entityManager 构建

private EntityManager entityManager

public List<ViewEmployeeBase> getCheckboxInfo(String evaluateYear) {
// criteriaBuilder用于构建CriteriaQuery的构建器对象
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// criteriaQuery包含查询语句的各个部分,如where、max、sum、groupBy、orderBy等
CriteriaQuery<ViewEmployeeBase> criteriaQuery = criteriaBuilder.createQuery(ViewEmployeeBase.class);
// 获取查询实例的属性,select * from books
Root<ViewEmployeeBase> root = criteriaQuery.from(ViewEmployeeBase.class);
// 相当于select type,max(price) maxPrice,sum(price) sumPrice from books中select 与
// from之间的部分
criteriaQuery.multiselect(root.get("position").as(String.class));
// where type = 1
criteriaQuery.where(criteriaBuilder.equal(root.get("id").get("evaluateYear"), evaluateYear));
// group by type
criteriaQuery.groupBy(root.get("position"));
// criteriaQuery拼成的sql是select type,max(price) maxPrice,sum(price) sumPrice from
// books group by type;查询出的列与对象BookInfo的属性对应
// 记录当前sql查询结果总条数
// List<ViewEmployeeBase> counts = entityManager.createQuery(criteriaQuery).getResultList();
// sql查询对象
TypedQuery<ViewEmployeeBase> createQuery = entityManager.createQuery(criteriaQuery);
return createQuery.getResultList();
// 设置分页参数
}

posted @ 2019-08-23 10:27  小傻孩丶儿  阅读(3583)  评论(0编辑  收藏  举报