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) |
|