💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
如果查询条件是变化的,这时就需要接口 Specification 来完成动态条件的构建了。 主要的接口是下面这两个。 ```java public interface JpaSpecificationExecutor<T> { Optional<T> findOne(Specification<T> spec); List<T> findAll(Specification<T> spec); Page<T> findAll(Specification<T> spec, Pageable pageable); List<T> findAll(Specification<T> spec, Sort sort); long count(Specification<T> spec); boolean exists(Specification<T> spec); long delete(Specification<T> spec); } ``` ```java public interface Specification<T> extends Serializable { ... /** * Root:查询的主实体,通过他获取主实体中的变量名 * CriteriaQuery:用来自定义查询,如 where、groupBy、orderBy等 * CriteriaBuilder:构建查询条件,如 and、or、equal等 */ @Nullable Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder); } ``` <br/> **示例1:** ```sql select count(id) from tb_person where username like '张%' and gender='男' ``` ```java Specification<Person> spec = (root, query, cBuilder) -> { Predicate p1 = cBuilder.like(root.get("username"), "张%"); Predicate p2 = cBuilder.equal(root.get("gender"), "男"); return cBuilder.and(p1, p2); }; long count = personRepository.count(spec); ``` <br/> **示例2:** ```sql select distinct * from tb_person where username like '张%' and gender='男' having age>= 24 ``` ```java Specification<Person> spec = (root, query, cBuilder) -> { Predicate p1 = cBuilder.like(root.get("username"), "张%"); Predicate p2 = cBuilder.equal(root.get("gender"), "男"); query.distinct(true); query.having(cBuilder.ge(root.get("age"), 24)); query.where(p1, p2); return query.getRestriction(); }; List<Person> personList = personRepository.findAll(spec); ``` <br/> **示例3:** ```sql select * from tb_person where username like '张%' and (gender='男' or age>= 24) ``` ```java Specification<Person> spec = (root, query, cBuilder) -> { Predicate p1 = cBuilder.like(root.get("username"), "张%"); Predicate p2 = cBuilder.equal(root.get("gender"), "男"); Predicate p3 = cBuilder.ge(root.get("age"), 24); List<Predicate> predicates = new ArrayList<>(16); predicates.add(p1); predicates.add(cBuilder.or(p2, p3)); query.where(predicates.toArray(new Predicate[predicates.size()])); return query.getRestriction(); }; List<Person> personList = personRepository.findAll(spec); ```