Inheritance spring-data-jpa query conditions to achieve the 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:

 

/ ** 
* Dynamic Conditions extracted in order to facilitate single method invocation
* @param
* @return
* /
Private Specification <the Lable> createSpecification (the Lable Lable) {

return new new Specification <the Lable> () {

@Override
public toPredicate the Predicate (Root <Lable> root, CriteriaQuery query, CriteriaBuilder cb) {<?>
// query for temporarily storing the collection
ArrayList <Predicate> List = new new ArrayList <> ();
IF (lable.getLabelname ()! = null && "! ".equals (lable.getLabelname ())) {
the Predicate the predicateA = cb.like (root.get (" labelName "),"% "+ lable.getLabelname () +"% "); // WHERE labelName like XXX% %
List.add (the predicateA);
}
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()));
}
 
   

 

Guess you like

Origin www.cnblogs.com/gdut-lss/p/11520072.html