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