最近抽出来一些时间来整理,最近用到的东西,这次主要是写一下 JPA 的动态实现多条件查询
这里就不贴全部的内容了,只贴出来了,关键代码
首先是 Dao,作为一个负责任的博主,我把引用的包也贴出来了,注意第一个 第二个 必须要有
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository public interface XXXXDao extends JpaRepository<实体类的名字, String>, JpaSpecificationExecutor<实体类的名字>, PagingAndSortingRepository<实体类的名字, String> { }然后就是接口实现类,中间的过程就省略掉了例如什么什么Service 和 Controller,XXXServiceImpl 层 直接贴出代码了。。Ps 虽然我只想扔个图上去,深度懒癌患者,数据类型传过来的时候一定要是 Page<实体类名称> 类型
@Override public Page<实体类名称> findAllPage(Pageable pageable,要传的参数 要传的参数) { //封装查询对象Specification 这是个自带的动态条件查询 Specification<实体类名称> spec = new Specification<实体类名称>() { @Override public Predicate toPredicate(Root<实体类名称> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { //定义集合来确定Predicate[] 的长度,因为CriteriaBuilder的or方法需要传入的是断言数组 List<Predicate> predicates = new ArrayList<Predicate>(); //对客户端查询条件进行判断,并封装Predicate断言对象 if(null != 要传的参数.getxxx()){ predicates.add(criteriaBuilder.like(root.get("xxx"), "%"+要传的参数.getxxx()+"%")); } return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } }; // 查询出全部数据源列表 return xxxxDao.findAll(spec,pageable); }ServiceIpl 引用包。。。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Optional;