Jpa的Dao层只继承Repository做复杂查询,不能做到不传某不一个条件,where子句根据条件是否为空动态设置条件。
类似Mybatis中的if判断:
<if test="createTime != null and createTime !=''" >
and a.create_time = #{createTime,jdbcType=VARCHAR}
</if>
解决
Dao层继承Repository同时继承JpaSpecificationExecutor实现动态设置查询条件:
public interface XxxDao extends JpaRepository<Xxx,Id>,JpaSpecificationExecutor<Xxx> {
}
JpaSpecificationExecutor接口已存在5个方法:
Optional<T> findOne(@Nullable Specification<T> var1);
List<T> findAll(@Nullable Specification<T> var1);
Page<T> findAll(@Nullable Specification<T> var1, Pageable var2);
List<T> findAll(@Nullable Specification<T> var1, Sort var2);
long count(@Nullable Specification<T> var1);
Dao查询直接使用上述5个方法任何一个,Specification对象直接内部类形式重写toPredicate方法:
@Override
//s,s1,s2为查询条件,前台不传就查询所有,s3为查询前多少条数据
public List<Xxx> queryXxxs(String s, String s1, String s2, int s3) {
//排序
Sort sort = new Sort(Sort.Direction.DESC,"sort","updateTime");
PageRequest pageRequest = PageRequest.of(0,s3,sort);
return XxxDao.findAll((Specification) (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(s)){
predicates.add(criteriaBuilder.like(root.get("genre").as(String.class),"%" + s + "%"));
}
if(StringUtils.isNotEmpty(s1)){
predicates.add(criteriaBuilder.like(root.get("subject").as(String.class),"%" + s1 + "%"));
}
if(StringUtils.isNotEmpty(s2)){
predicates.add(criteriaBuilder.like(root.get("no").as(String.class),"%" + s2 + "%"));
}
Predicate[] predicate = new Predicate[predicates.size()];
return criteriaBuilder.and(predicates.toArray(predicate));
},pageRequest).getContent();
}
·