参考:https://blog.csdn.net/cmw1085215666/article/details/82946712

 

要点:  

Repository:
*//此接口继承JpaRepository和JpaSpecificationExecutor**
public interface WorkTableRepository  extends JpaRepository<MilestoneInfo, String> ,JpaSpecificationExcutor<MilestoneInfo>{}

 



@Service
public class JJJJJJJService {
    @Autowired
    private WorkTableRepository workTableRepository;
//分页查询
public Page<MilestoneInfo> queryPage(int page, int size, Map whereMap){
        Specification<MilestoneInfo> specification = createWhere(whereMap);
        PageRequest pageRequest=PageRequest.of(page-1,size);
      return   workTableRepository.findAll(specification,pageRequest);
    }

    /**
     * 动态构建查询条件
     * @param searchMap
     */
    private Specification<MilestoneInfo> createWhere(Map searchMap){

       return new Specification<MilestoneInfo>() {
           @Override
           public Predicate toPredicate(Root<MilestoneInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
               List<Predicate> predicateList = new ArrayList<Predicate>();
               System.err.println("*********id:"+searchMap.get("id"));
               //id
               if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                   predicateList.add(criteriaBuilder.equal(root.get("id").as(Long.class),(Long)searchMap.get("id")));
               }
               System.err.println("***name:"+searchMap.get("name"));
               //name
               if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                   predicateList.add(criteriaBuilder.like(root.get("name").as(String.class),"%"+(String)searchMap.get("name")+"%"));
               }
               //注意criteriaBuilder.or表示两个查询条件之间是or;cb.and表示查询条件之间是and关系
               return criteriaBuilder.or(predicateList.toArray(new Predicate[predicateList.size()]));
           }
       };
    }
}

 

 
posted on 2019-06-21 10:16  lshan  阅读(764)  评论(0编辑  收藏  举报