• 继承spring-data-jpa 的paSpecificationExecutor实现条件查询


    dao:

    package com.tensquare.base.dao;
    import com.tensquare.base.pojo.Lable;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    public interface LableDao extends JpaRepository<Lable,String>, JpaSpecificationExecutor<Lable> {

    }

    service:

    /**
    * 动态条件构建 提取出单独的方法 为了方便调用
    * @param
    * @return
    */
    private Specification<Lable> createSpecification(Lable lable) {

    return new Specification<Lable>() {

    @Override
    public Predicate toPredicate(Root<Lable> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    //用于暂时存放查询条件的集合
    ArrayList<Predicate> list = new ArrayList<>();
    if (lable.getLabelname()!=null&&!"".equals(lable.getLabelname())){
    Predicate predicate = cb.like(root.get("labelname"), "%" + lable.getLabelname() + "%");//where labelname like %xxx%
    list.add(predicate);
    }
    if (lable.getState()!=null&&!"".equals(lable.getState())){
    Predicate predicate = cb.equal(root.get("state"), lable.getState() );//where state = xxx
    list.add(predicate);
    }
    //最终将查询条件拼好然后return
    Predicate[] predicates = new Predicate[list.size()];
    return cb.and( list.toArray(predicates));//where labelname like %xxx% and state = xxx

    }
    };

    }

    不分页:
    public List<Lable> findSearch(Lable lable) {
    //Spring Data JPA使用JpaSpecificationExecutor构建条件查询
    return lableDao.findAll(createSpecification(lable));
    }

    分页:
    public Page<Lable> pageQuery(int pageNum, int size, Lable lable) {
    //封装分页对象
    Pageable pageable = PageRequest.of(pageNum - 1, size);
    return lableDao.findAll(createSpecification(lable),pageable);
    }



    controller:

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    public Result findSearch(@RequestBody Lable lable){
    List<Lable> lables = lableService.findSearch(lable);
    return new Result(true,StatusCode.OK,"查询成功",lables);
    }

    @RequestMapping(value = "/search/{pageNum}/{size}",method = RequestMethod.POST)
    public Result pageQuery(@PathVariable int pageNum,@PathVariable int size,@RequestBody Lable lable){
    Page<Lable> pages = lableService.pageQuery(pageNum,size,lable);
    return new Result(true,StatusCode.OK,"查询成功",new PageResult<Lable>(pages.getTotalElements(),pages.getContent()));
    }
     
       
  • 相关阅读:
    iOS开发数据库篇—FMDB简单介绍
    iOS开发数据库篇—SQLite常用的函数
    IOS开发数据库篇—SQLite模糊查询
    iOS开发数据库篇—SQLite的应用
    iOS开发数据库篇—SQL代码应用示例
    iOS开发数据库篇—SQL
    iOS开发数据库篇—SQLite简单介绍
    江苏建工信息化继续规划
    武汉分公司年终检查
    分公司资金查询
  • 原文地址:https://www.cnblogs.com/gdut-lss/p/11520072.html
Copyright © 2020-2023  润新知