JPA——根据条件分页查询实现方法

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 * 下载记录
 */
@Service
public class ExcelDownloadServiceImpl {

    @Autowired
    ExcelDownloadRepo excelDownloadRepo;

    /*
    分页查询
     */
    public Page<ExcelDownload> getMore(PageQuery query, ExcelDownload excelDownload) {
        PageRequest pageable = new PageRequest(query.getPindex(), query.getPcount(), query.getSortObj());
        Specification<ExcelDownload> spe = getSpecification(excelDownload);
        Page<ExcelDownload> page = excelDownloadRepo.findAll(Specifications.where(spe), pageable);
        return page;
    }

    public Specification<ExcelDownload> getSpecification(ExcelDownload excelDownload) {
        Specification<ExcelDownload> spe = new Specification<ExcelDownload>() {
            @Override
            public Predicate toPredicate(Root<ExcelDownload> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();

                if (StringUtils.isNotBlank(excelDownload.getModule())) {
                    list.add(cb.equal(root.get("module").as(String.class), excelDownload.getModule()));
                }
                if (StringUtils.isNotBlank(excelDownload.getDownloadState())) {
                    list.add(cb.equal(root.get("downloadState").as(String.class), excelDownload.getDownloadState()));
                }
                if(null != excelDownload.getStartDate()){
                    list.add(cb.greaterThanOrEqualTo(root.<Date> get("createTime"), excelDownload.getStartDate()));
                }
                if(null != excelDownload.getEndDate()){
                    list.add(cb.lessThanOrEqualTo(root.get("createTime"),excelDownload.getEndDate()));
                }

                Predicate[] p = new Predicate[list.size()];
                query.where(cb.and(list.toArray(p)));
                query.orderBy(cb.desc(root.get("id").as(Long.class)));
                return query.getRestriction();
            }
        };
        return spe;
    }
}

  

上一篇:不同炭材料对铅炭负极的性能影响


下一篇:Restful framework【第十二篇】版本控制