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

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


}



  • 1
    点赞
  • 2
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值