JPA——根据条件分页查询实现方法
2021/4/9 10:25:23
本文主要是介绍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——根据条件分页查询实现方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)