1、最基础的查询
CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> root = cq.from(User.class); //from User cq.select(root); //select * from User javax.persistence.criteria.Predicate pre = cb.equal(root.get("id").as(Integer.class),id);//id=1 cq.where(pre);//where id=1 Query query = entityManager.createQuery(cq);//select u from User u where u.id = 1 System.out.println(query.getResultList());
2、spring data jpa 的 toPredicate 方法
public Predicate toPredicate(Root<RoleEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<Predicate>(); list.add(cb.equal(root.get("dr").as(Integer.class), delete)); if (StringUtils.isNotBlank(searchParam)) {/*searchParam 为传递参数*/ list.add(cb.or(cb.like(root.get("roleName").as(String.class), cb.literal("%" + searchParam + "%")), cb.like(root.get("roleCode").as(String.class), cb.literal("%" + searchParam + "%")))); } // 角色id if (roleId != null && !("".equals(roleId.trim()))) { list.add(cb.equal(root.get("id").as(String.class), roleId)); } // 管理员角色标识 if (category != null && category > 0) { list.add(cb.equal(root.get("category").as(Integer.class), category)); } //多角色Id if (roleids != null && roleids.size() > 0) { list.add(root.get("id").as(String.class).in(roleids)); } Predicate[] predicates = new Predicate[list.size()]; query.where(list.toArray(predicates)); query.orderBy(cb.asc(root.get("roleType").as(String.class)), cb.asc(root.get("roleProperty").as(String.class)), cb.asc(root.get("roleCode").as(String.class))); return query.getRestriction(); }
参考 org.springframework.data.jpa.repository.support.SimpleJpaRepository 的 findAll方法,如下
public List<T> findAll(Specification<T> spec) { return getQuery(spec, (Sort) null).getResultList(); } protected TypedQuery<T> getQuery(Specification<T> spec, Sort sort) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<T> query = builder.createQuery(getDomainClass()); Root<T> root = applySpecificationToCriteria(spec, query); query.select(root); if (sort != null) { query.orderBy(toOrders(sort, root, builder)); } return applyRepositoryMethodMetadata(em.createQuery(query)); } private TypedQuery<T> applyRepositoryMethodMetadata(TypedQuery<T> query) { if (metadata == null) { return query; } LockModeType type = metadata.getLockModeType(); TypedQuery<T> toReturn = type == null ? query : query.setLockMode(type); applyQueryHints(toReturn); return toReturn; }