欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 复杂多条件分页排序列表查询

程序员文章站 2022-04-25 19:46:52
...

Controller层就不写了,主要贴一下Service代码。

Service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

@Service("operatingRecordService")
@Transactional
public class OperatingRecordService {

	 @Autowired
	 private OperatingRecordRepository operatingRecordRepository;


	/**
	 * 分页列表模糊 查询
	 * 
	 * @param page
	 * @param rows
	 * @param operatingRecordVO
	 * @return
	 */
	public Page<OperatingRecordVO> findPageList(Integer page,Integer rows,OperatingRecordVO operatingRecordVO){
		page = (page == null) ? 1 : page;
		rows = (rows == null) ? 10 : rows;

		Pageable pageable = new PageRequest(page - 1, rows, Sort.Direction.DESC,"id");//id倒序排列
		return (Page<OperatingRecordVO>) operatingRecordRepository.findAll(new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query,
										 CriteriaBuilder cb) {

				
				//操作对象 模糊查询
				if (!StringUtil.isBlank(operatingRecordVO.getObjects())) {
					Predicate objects ;
					objects = cb.like(root.get("objects"), "%"+operatingRecordVO.getObjects()+"%");
					query.where(objects);
				}
				//操作类型  精确查询
				if (operatingRecordVO.getType()!= null && !"".equals(operatingRecordVO.getType())) {
					Predicate type ;
					type = cb.equal(root.get("type"), operatingRecordVO.getType());
					query.where(type);
				}
				
				//操作状态
				if (operatingRecordVO.getStatus()!= null && !"".equals(operatingRecordVO.getStatus())) {
					Predicate status ;
					status = cb.equal(root.get("status"), operatingRecordVO.getStatus());
					query.where(status);
				}
				return null;
			};
		}, pageable);
	};
}

OperatingRecordRepository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional(propagation = Propagation.NESTED)
public interface OperatingRecordRepository extends JpaRepository<OperatingRecordVO, Integer> , JpaSpecificationExecutor<OperatingRecordVO> {


}