Java教程

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

本文主要是介绍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;
    }
}

  

这篇关于JPA——根据条件分页查询实现方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!