Java : Hibernate 动态+分页+自定义字段+自定义实体类查询

// 组合查询
public List<ListBookDTO> listSetDSL(PublishingHouse publishingHouse,Integer minDiscount, Integer maxDiscount, Integer minStocks, Integer maxStocks, Integer page, Integer pageSize) {
CriteriaBuilder builder = em.getCriteriaBuilder();
// 指明返回类型
CriteriaQuery<ListBookDTO> criteriaQuery = builder.createQuery(ListBookDTO.class);
Root<Book> root = criteriaQuery.from(Book.class);
// 动态条件
List<Predicate> pList = new ArrayList<>();
if (publishingHouse != null) {
pList.add(builder.isNotNull(root.get("publishingHouse")));
pList.add(builder.equal(root.get("publishingHouse").as(PublishingHouse.class), publishingHouse));
}
if (minDiscount != null) {
pList.add(builder.isNotNull(root.get("discount")));
pList.add(builder.greaterThan(root.get("discount"), minDiscount));
}
if (minDiscount == null && maxDiscount != null) {
pList.add(builder.isNotNull(root.get("discount")));
pList.add(builder.lessThan(root.get("discount"), maxDiscount));
}
if (minStocks != null) {
pList.add(builder.isNotNull(root.get("stocks")));
pList.add(builder.greaterThan(root.get("stocks"), minStocks));
}
if (maxStocks != null) {
pList.add(builder.isNotNull(root.get("stocks")));
pList.add(builder.lessThan(root.get("stocks"), maxStocks));
}
Predicate[] predicates = new Predicate[pList.size()];
criteriaQuery.where(builder.and(pList.toArray(predicates))); // 条件
criteriaQuery.orderBy(builder.desc(root.get("id"))); // 排序
criteriaQuery.select(builder.construct(ListBookDTO.class,root.get("id"), root.get("name"), root.get("publishingHouse")));
TypedQuery<ListBookDTO> query = em.createQuery(criteriaQuery);
query.setFirstResult(page - 1).setMaxResults(pageSize); // 分页
return query.getResultList();
}
posted @ 2019-07-31 18:12  cccy0  阅读(859)  评论(0编辑  收藏  举报