条件查询
criteria.where() 里面的条件可以是条件数组 如下所示
public Optional< SysOrgQrcodeConfig> findByQrTitle(String title, String orgPid) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SysOrgQrcodeConfig> criteria = builder.createQuery(SysOrgQrcodeConfig.class);
Root<SysOrgQrcodeConfig> root = criteria.from(SysOrgQrcodeConfig.class);
criteria.select(root);
criteria.where(builder.equal(root.get("title"), title), builder.equal(root.get("orgPid"), orgPid));
return entityManager
.unwrap(Session.class)
.createQuery(criteria)
.uniqueResultOptional();
}
存在多条件查询
条件集合存储
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public Page<GroupDetails> findAllByPage(String uid, String title, LocalDateTime startTime, LocalDateTime endTime, Pageable pageable) {
return repository.findAll((root, query, criteriaBuilder) -> {
List<Predicate> predicateList = new ArrayList<>();
predicateList.add(criteriaBuilder.equal(root.get("userPid"), uid));
if (startTime != null || endTime != null) {
predicateList.add(criteriaBuilder.between(root.get("createTime"), startTime, endTime));
}
if (title != null && !title.isEmpty()) {
predicateList.add(criteriaBuilder.like(root.get("groupName"), "%" + title + "%"));
}
if (predicateList.size() > 0) {
Predicate[] predicates = new Predicate[predicateList.size()];
for (int i = 0; i < predicates.length; i++) {
predicates[i] = predicateList.get(i);
}
query.where(predicates);
}
query.orderBy(criteriaBuilder.desc(root.get("createTime")));
return query.getRestriction();
}, pageable);
}