【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现
一.不带有动态条件的查询 分页的实现
实例代码:
controller:返回的是Page<>对象
- @Controller
- @RequestMapping(value = "/egg")
- public class EggController {
- @ResponseBody
- @RequestMapping(value = "/statisticsList")
- public Page<StatisticsDto> statisticsList(@RequestParam("actId") Long actId,HttpServletRequest request,
- Pageable pageable){
- Long entId = CasUtils.getEntId(request);
- return eggService.findStatisticsWithPage(entId,actId,pageable) ;
- }
- }
serviceImpl中的实现方法:这里需要查询出数据的数量total,以及查询到的数据list,最后new一个实现类 new PageImpl(list,pageable,total)
Page 的实现类是PageImpl Pageable 的实现类是PagerRequest
- public Page<StatisticsDto> findStatisticsWithPage(Long entId, Long actId, Pageable pageable) {
- int total = wactPlayRecordDao.findDistinctPlayRecordTotal(entId, actId);
- // List<String> openIdList = wactPlayRecordDao.findDistinctPlayRecordList(entId, actId);
- List<WactPlayRecord> wactPlayRecordList = wactPlayRecordDao.findDistinctPlayRecordList(entId,actId);
- List<StatisticsDto> statisticsDtoList = new ArrayList<>();
- if (wactPlayRecordList.size()>0){
- // statisticsDtoList = new ArrayList<>(wactPlayRecordList.size());
- for (WactPlayRecord wactPlayRecord:wactPlayRecordList){
- StatisticsDto statisticsDto = new StatisticsDto();
- String openid = wactPlayRecord.getOpenid();
- Long playRecordId = wactPlayRecord.getId();
- Mpuser mpuser = mpuserDao.findMpUserByOpenId(openid);
- List<CustomerCollItemInfo> customerCollItemInfoList = customerCollitemInfoDao.findCustomerCollItemInfoByOpenId(openid,entId,actId,playRecordId);
- List<CustCollItemsInfoDto> custCollItemsInfoDtoList = new ArrayList<>();
- if (customerCollItemInfoList.size()>0){
- statisticsDto.setDetailIsShow("able");
- custCollItemsInfoDtoList = new ArrayList<>(customerCollItemInfoList.size());
- for (CustomerCollItemInfo customerCollItemInfo:customerCollItemInfoList){
- CustCollItemsInfoDto custCollItemsInfoDto = new CustCollItemsInfoDto(customerCollItemInfo);
- custCollItemsInfoDtoList.add(custCollItemsInfoDto);
- }
- }else{
- //已中奖但是未填写&&未中奖
- statisticsDto.setDetailIsShow("unable");
- }
- if (wactPlayRecord.getIsWin()==0){
- wactPlayRecord.setIsUse(2);
- }
- WactPlayRecordDto wactPlayRecordDto = new WactPlayRecordDto(wactPlayRecord);
- MpuserDto mpuserDto = null;
- if (mpuser!= null){
- mpuserDto = new MpuserDto(mpuser);
- }
- statisticsDto.setWactPlayRecordDto(wactPlayRecordDto);
- statisticsDto.setCustCollItemsInfoDtoList(custCollItemsInfoDtoList);
- statisticsDto.setMpuserDto(mpuserDto);
- statisticsDtoList.add(statisticsDto);
- }
- }
- return new PageImpl(statisticsDtoList,pageable,total);
- }
dao:需要继承JpaRepository
- public interface WactPlayRecordDao extends JpaRepository<WactPlayRecord, Long>{
- @Query("FROM WactPlayRecord w WHERE w.entId = :endId AND w.actId = :actId AND w.status = 1")
- List<WactPlayRecord> findDistinctPlayRecordList(@Param("endId") Long endId,@Param("actId") Long actId);
- <pre name="code" class="java">@Query("SELECT count(w.openid) FROM WactPlayRecord w WHERE w.entId = :endId AND w.actId = :actId AND w.status = 1")
- int findDistinctPlayRecordTotal(@Param("endId") Long endId,@Param("actId") Long actId);
}
二。带有查询条件,两种方法
方式1(使用与查询条件在一个实体类中).:
controller:同样是返回的Page<>对象 ,增加了表单提交的数据对象
- @Controller
- @RequestMapping("/news")
- public class NewsController {
- private NewsService newsService;
- private NewsCategoryService newsCategoryService;
- @RequestMapping("/list")
- @ResponseBody
- public Page<NewsDto> list(Pageable pageable, NewsCondition newsCondition) {
- Long id = AppUtils.getBean("loginInfo", LoginInfo.class).getEntId();
- newsCondition.setEntId(id);
- return newsService.find(newsCondition, pageable);
- }
serviceImpl
- @Service
- public class NewsServiceImpl implements NewsService {
- @Override
- @Transactional(readOnly = true)
- public Page<NewsDto> find(final NewsCondition condition, Pageable pageable) {
- Page<NewsEntity> page = newsDao.findAll(new Specification<NewsEntity>() {
- @Override
- public Predicate toPredicate(Root<NewsEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
- List<Predicate> list = new ArrayList<>();
- list.add(cb.equal(root.get("entId").as(Long.class), condition.getEntId()));
- list.add(cb.equal(root.get("deleted").as(Boolean.class), false));
- Join<NewsEntity, NewsCategoryEntity> newsCategoryJoin = root.join("newsCategory");
- list.add(cb.equal(newsCategoryJoin.get("enable").as(Boolean.class), true));
- list.add(cb.equal(newsCategoryJoin.get("deleted").as(Boolean.class), false));
- if (condition.getCategoryId() != null) {
- list.add(cb.equal(newsCategoryJoin.get("id").as(Long.class), condition.getCategoryId()));
- }
- if (StringUtils.isNotBlank(condition.getTitle())) {
- list.add(cb.like(root.get("title").as(String.class), "%" + condition.getTitle() + "%"));
- }
- if (condition.getFromDate() != null) {
- list.add(cb.greaterThanOrEqualTo(root.get("createdDate").as(Date.class), DateUtils.getDateWithStartSecond(condition.getFromDate())));
- }
- if (condition.getToDate() != null) {
- list.add(cb.lessThanOrEqualTo(root.get("createdDate").as(Date.class), DateUtils.getDateWithLastSecond(condition.getToDate())));
- }
- query.orderBy(cb.desc(root.get("top")), cb.desc(root.get("id")));
- Predicate[] predicates = new Predicate[list.size()];
- predicates = list.toArray(predicates);
- return cb.and(predicates);
- }
- }, pageable);
- if (page.hasContent()) {
- List<NewsEntity> newsEntities = page.getContent();
- List<NewsDto> newsDtos = new ArrayList<>(newsEntities.size());
- List<Long> pids = new ArrayList<>();
- for (NewsEntity newsEntity : newsEntities) {
- if (newsEntity.getTitleImage() != null) {
- pids.add(newsEntity.getTitleImage());
- }
- }
- Map<Long, MediaFileEntity> map = null;
- if (CollectionUtils.isNotEmpty(pids)) {
- map = mediaFileDao.findWithMap(pids);
- }
- for (NewsEntity newsEntity : newsEntities) {
- newsDtos.add(new NewsDto(newsEntity, map != null ? map.get(newsEntity.getTitleImage()) : null));
- }
- return new PageImpl(newsDtos, pageable, page.getTotalElements());
- }
- return null;
- }
- }
dao:这里一定要继承JpasSpecificationExecutor,然后使用其中的findAll()方法,其中封装了分页方法,排序方法等
- public interface NewsDao extends JpaRepository<NewsEntity, Long>, JpaSpecificationExecutor<NewsEntity> {
- }
方式二(查询条件在不同表中的情形):底层DAO使用sql拼装,service中仍然使用new PageImpl的方法
controller
- @Controller
- @RequestMapping(value = "/egg")
- public class EggController {
- @ResponseBody
- @RequestMapping(value = "/statisticsList")
- public Page<StatisticsDto> statisticsList(@RequestParam("actId") Long actId,HttpServletRequest request,
- Pageable pageable,StatisticsCondition statisticsCondition){
- Long entId = CasUtils.getEntId(request);
- return eggService.findStatisticsWithPage(entId,actId,pageable,statisticsCondition) ;
- }
serviceImpl
- @Override
- @Transactional
- public Page<StatisticsDto> findStatisticsWithPage(Long entId, Long actId, Pageable pageable, StatisticsCondition statisticsCondition) {
- Long total = wactPlayRecordDao.findTotalByCondition(entId,actId,
- statisticsCondition.getParticipateBegin(),statisticsCondition.getParticipateEnd()
- ,statisticsCondition.getTelephone(),statisticsCondition.getIsWin(),statisticsCondition.getIsUse());
- List<StatisticsDto> statisticsDtoList = new ArrayList<>();
- if (total >0){
- List<Object[]> objectList = wactPlayRecordDao.findStatisticsByConditionWithPage(entId,actId,
- statisticsCondition.getParticipateBegin(),statisticsCondition.getParticipateEnd()
- ,statisticsCondition.getTelephone(),statisticsCondition.getIsWin(),statisticsCondition.getIsUse(),pageable);
- for (Object[] obj:objectList){
- StatisticsDto statisticsDto = new StatisticsDto();
- Long id = new BigInteger(obj[0].toString()).longValue();
- Integer isWin = new Short(obj[1].toString()).intValue();
- Integer isUse = new Short(obj[2].toString()).intValue();
- String createdDateStr = com.raipeng.micro.core.utils.DateUtils.format((Date)obj[4], com.raipeng.micro.core.utils.DateUtils.PATTERN_2);
- WactAwards wactAwards = new WactAwards();
- Long awardsId = new BigInteger(obj[5].toString()).longValue();
- if (awardsId != 0l){
- wactAwards = wactAwardsDao.findAwardByAwardId(awardsId);
- }
- if (isWin == 0){
- isUse = 2;
- }
- WactPlayRecordDto wactPlayRecordDto = new WactPlayRecordDto(id,isWin,isUse,(String)obj[3],wactAwards.getName(),wactAwards.getGradeName(),createdDateStr);
- String openid = (String)obj[3];
- Long playRecordId = wactPlayRecordDto.getId();
- List<CustomerCollItemInfo> customerCollItemInfoList = customerCollitemInfoDao.findCustomerCollItemInfoByPlayRecordId(playRecordId);
- List<CustCollItemsInfoDto> custCollItemsInfoDtoList = new ArrayList<>();
- if (customerCollItemInfoList.size()>0){
- statisticsDto.setDetailIsShow("able");
- custCollItemsInfoDtoList = new ArrayList<>(customerCollItemInfoList.size());
- for (CustomerCollItemInfo customerCollItemInfo:customerCollItemInfoList){
- // customerCollItemsIds +=customerCollItemInfo.getCustomerCollectitemsId()+"#";
- CustCollItemsInfoDto custCollItemsInfoDto = new CustCollItemsInfoDto(customerCollItemInfo);
- custCollItemsInfoDtoList.add(custCollItemsInfoDto);
- }
- }else{
- //已中奖但是未填写&&未中奖
- statisticsDto.setDetailIsShow("unable");
- }
- Object[] object = wactPlayRecordDao.findUserInfoByOpenId(openid);
- MpuserDto mpuserDto = new MpuserDto();
- if (object[1] != null){
- mpuserDto.setHeadImg((String)object[1]);
- }else if (object[3] != null){
- mpuserDto.setHeadImg((String)object[3]);
- }else {
- mpuserDto.setHeadImg("");
- }
- if (object[2] != null){
- mpuserDto.setNickName((String)object[2]);
- }else if (object[4] != null){
- mpuserDto.setNickName((String)object[4]);
- }else {
- mpuserDto.setNickName("");
- }
- if (wactPlayRecordDto.getIsWin()=="已中奖" && custCollItemsInfoDtoList.size()==0){
- wactPlayRecordDto.setIsUse("");
- }
- if (mpuserDto.getHeadImg()==""){
- statisticsDto.setHeadImg("unable");
- }else{
- statisticsDto.setHeadImg("able");
- }
- if (wactPlayRecordDto.getIsUse()=="已领取"){
- statisticsDto.setHaveReceived("able");
- }else {
- statisticsDto.setHaveReceived("unable");
- }
- statisticsDto.setWactPlayRecordDto(wactPlayRecordDto);
- statisticsDto.setCustCollItemsInfoDtoList(custCollItemsInfoDtoList);
- statisticsDto.setMpuserDto(mpuserDto);
- if (wactPlayRecordDto.getIsUse()=="未领取"){
- statisticsDto.setSetReceive("able");
- }else {
- statisticsDto.setSetReceive("unable");
- }
- String customerCollItemsIds = "";
- List<CustomerCollectItems> customerCollectItemsList = customerCollectItemsDao.findListByActivityId(actId);
- if (customerCollectItemsList != null && customerCollectItemsList.size()>0){
- for (CustomerCollectItems customerCollectItems:customerCollectItemsList){
- customerCollItemsIds += customerCollectItems.getCollectItemsId()+"#";
- }
- }
- statisticsDto.setCustomerCollectItemsIds(customerCollItemsIds);
- statisticsDtoList.add(statisticsDto);
- }
- }
- return new PageImpl<StatisticsDto>(statisticsDtoList,pageable,total);
- }
dao daoplus daoImpl(dao继承daoPlus,daoImpl实现daoPlus)
daoplus
- public interface WactPlayRecordPlusDao {
- Long findTotalByCondition(Long entId,Long actId,Date participateBegin,Date participateEnd,String telephone,Integer isWin,Integer isUse);
- List<Object[]> findStatisticsByConditionWithPage(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse,Pageable pageable);
- }
daoImpl
- public class WactPlayRecordDaoImpl implements WactPlayRecordPlusDao {
- @PersistenceContext
- private EntityManager entityManager;
- public void setEntityManager(EntityManager entityManager) {
- this.entityManager = entityManager;
- }
- @Override
- public Long findTotalByCondition(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse) {
- StringBuffer sql = null;
- if (telephone != null && !"".equals(telephone)){
- // hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,W.openid " +//表没有关联所以不能使用面向对象语句的left outer join inner join 等
- // "FROM WactPlayRecord w inner join CustomerCollItemInfo c " +
- // "ON w.id = c.playRecordId" +
- // "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " +
- // "AND c.entId = :entId AND c.actId = :actId AND c.status = 1 And c.val = :telephone ");
- sql =new StringBuffer("SELECT count(p.id)" +
- "FROM rp_act_play_record p inner join rp_act_customer_collitem_info c " +
- "ON p.id = c.play_record_id " +
- "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " +
- "AND c.ent_id = :entId AND c.act_id = :actId AND c.status = 1 And c.val = :telephone ");
- }else {
- // hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,w.openid " +
- // "FROM WactPlayRecord w " +
- // "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " );
- sql = new StringBuffer("SELECT count(p.id) " +
- "FROM rp_act_play_record p " +
- "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " );
- }
- if (participateBegin != null){
- sql.append("AND p.created_date >= :participateBegin ");
- }
- if (participateEnd != null){
- sql.append("AND p.created_date <= :participateEnd ");
- }
- if (isWin == 0){
- sql.append("AND p.is_win = 0 ");
- }else if (isWin ==1){
- sql.append("AND p.is_win = 1 ");
- }
- if (isUse == 0){
- sql.append("AND p.is_use = 0 ");
- }else if (isUse == 1){
- sql.append("AND p.is_use = 1 ");
- }
- sql.append("order by p.created_date ASC");
- Query query = entityManager.createNativeQuery(sql.toString());
- query.setParameter("entId", entId).setParameter("actId", actId);
- if (participateBegin != null){
- query.setParameter("participateBegin", participateBegin);
- }
- if (participateEnd != null){
- query.setParameter("participateEnd", participateEnd);
- }
- if (telephone != null && !"".equals(telephone)){
- query.setParameter("telephone",telephone);
- }
- Long total = new BigInteger(query.getSingleResult().toString()).longValue();
- return total;
- }
- @Override
- public List<Object[]> findStatisticsByConditionWithPage(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse,Pageable pageable) {
- StringBuffer sql = null;
- if (telephone != null && !"".equals(telephone)){
- // hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,W.openid " +
- // "FROM WactPlayRecord w inner join CustomerCollItemInfo c " +
- // "ON w.id = c.playRecordId" +
- // "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " +
- // "AND c.entId = :entId AND c.actId = :actId AND c.status = 1 And c.val = :telephone ");
- sql =new StringBuffer("SELECT p.id,p.is_win,p.is_use,p.openid,p.created_date,p.awards_id " +
- "FROM rp_act_play_record p inner join rp_act_customer_collitem_info c " +
- "ON p.id = c.play_record_id " +
- "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " +
- "AND c.ent_id = :entId AND c.act_id = :actId AND c.status = 1 And c.val = :telephone ");
- }else {
- // hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,w.openid " +
- // "FROM WactPlayRecord w " +
- // "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " );
- sql = new StringBuffer("SELECT p.id,p.is_win,p.is_use,p.openid,p.created_date,p.awards_id " +
- "FROM rp_act_play_record p " +
- "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " );
- }
- if (participateBegin != null){
- sql.append("AND p.created_date >= :participateBegin ");
- }
- if (participateEnd != null){
- sql.append("AND p.created_date <= :participateEnd ");
- }
- if (isWin == 0){
- sql.append("AND p.is_win = 0 ");
- }else if (isWin ==1){
- sql.append("AND p.is_win = 1 ");
- }
- if (isUse == 0){
- sql.append("AND p.is_use = 0 ");
- }else if (isUse == 1){
- sql.append("AND p.is_use = 1 ");
- }
- sql.append("order by p.created_date DESC");
- Query query = entityManager.createNativeQuery(sql.toString());
- query.setParameter("entId", entId).setParameter("actId", actId);
- if (participateBegin != null){
- query.setParameter("participateBegin", participateBegin);
- }
- if (participateEnd != null){
- query.setParameter("participateEnd", participateEnd);
- }
- if (telephone != null && !"".equals(telephone)){
- query.setParameter("telephone",telephone);
- }
- query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
- query.setMaxResults(pageable.getPageSize());
- List<Object[]> objectList = query.getResultList();
- return objectList;
- }
【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现的更多相关文章
- springboot集成Spring Data JPA数据查询
1.JPA介绍 JPA(Java Persistence API)是Sun官方提出的Java持久化规范.它为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据.它的出现主要是为 ...
- 使用Spring Data JPA的Specification构建数据库查询
Spring Data JPA最为优秀的特性就是可以通过自定义方法名称生成查询来轻松创建查询SQL.Spring Data JPA提供了一个Repository编程模型,最简单的方式就是通过扩展Jpa ...
- 转:使用 Spring Data JPA 简化 JPA 开发
从一个简单的 JPA 示例开始 本文主要讲述 Spring Data JPA,但是为了不至于给 JPA 和 Spring 的初学者造成较大的学习曲线,我们首先从 JPA 开始,简单介绍一个 JPA 示 ...
- 了解 Spring Data JPA
前言 自 JPA 伴随 Java EE 5 发布以来,受到了各大厂商及开源社区的追捧,各种商用的和开源的 JPA 框架如雨后春笋般出现,为开发者提供了丰富的选择.它一改之前 EJB 2.x 中实体 B ...
- Spring Data JPA
转自: http://www.cnblogs.com/WangJinYang/p/4257383.html Spring 框架对 JPA 的支持 Spring 框架对 JPA 提供的支持主要体现在如下 ...
- 使用 Spring Data JPA 简化 JPA 开发
从一个简单的 JPA 示例开始 本文主要讲述 Spring Data JPA,但是为了不至于给 JPA 和 Spring 的初学者造成较大的学习曲线,我们首先从 JPA 开始,简单介绍一个 JPA 示 ...
- Spring Data JPA 梳理 - 使用方法
1.下载需要的包. 需要先 下载Spring Data JPA 的发布包(需要同时下载 Spring Data Commons 和 Spring Data JPA 两个发布包,Commons 是 Sp ...
- spring data jpa使用详解
https://blog.csdn.net/liuchuanhong1/article/details/52042477 使用Spring data JPA开发已经有一段时间了,这期间学习了一些东西, ...
- Spring Data JPA基本了解
前言 自 JPA 伴随 Java EE 5 发布以来,受到了各大厂商及开源社区的追捧,各种商用的和开源的 JPA 框架如雨后春笋般出现,为开发者提供了丰富的选择.它一改之前 EJB 2.x 中实体 B ...
- SpringBoot学习笔记:Spring Data Jpa的使用
更多请关注公众号 Spring Data Jpa 简介 JPA JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR ...
随机推荐
- [LeetCode] 905. Sort Array By Parity 按奇偶排序数组
Given an array A of non-negative integers, return an array consisting of all the even elements of A, ...
- 2019 SDN上机第1次作业
一.安装轻量级网络仿真工具Mininet 克隆github上的Mininet源 git clone https://github.com/mininet/mininet 选择默认全部安装 cd min ...
- 【微信小程序】手写索引选择器(城市列表,汽车品牌选择列表)
摘要: 小程序索引选择器,点击跳转相应条目,索引可滑动,滑动也可跳转 场景:城市选择列表, 汽车品牌选择列表 所用组件: scroll-view(小程序原生) https://developers.w ...
- Spring Cloud(十四):Ribbon实现客户端负载均衡及其实现原理介绍
年后到现在一直很忙,都没什么时间记录东西了,其实之前工作中积累了很多知识点,一直都堆在备忘录里,只是因为近几个月经历了一些事情,没有太多的经历来写了,但是一些重要的东西,我还是希望能坚持记录下来.正好 ...
- spring bean的三种管理方式·
1.无参构造函数 1.xml文件配置内容 <!--无参构造函数--> <bean id="bean1" class="com.imooc.ioc.dem ...
- 动态引用存储——集合&&精确的集合定义——泛型
1,集合宏观理解 1.1,为什么引入集合? 对于面向对象的语言来说,操作对象的功能不可或缺. 为了方便对对象进行操作和处理,就必须要对对象进行暂时的存储.[数据最终存在数据库里] 使用数组来存储对象的 ...
- Spring Boot Swagger2自动生成接口文档
一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 1.问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 2 ...
- TortoiseSVN客户端更改新的URL和账号
一: 变更SVN地址 右键(TortoiseSVN) → Relocate → 输入你新的URL地址 二:变更账号 TortoiseSVN右键->Setting 进入“Setting”之后,也就 ...
- linux服务器的SSH 配置
远程连接服务器: 就是通过文字或图形接口的方式来远程登陆另外一台服务器系统,让你在远程的终端前面登陆linux 主机以取得可操作主机的接口 主要的远程连接服务器的主要类型: 1)文字接口明文传输 : ...
- Unity3d—GUI能量条
1.打开Unity编辑器. 2.在脚本文件夹中添加C#脚本,我的是添加了skill_01这个脚本.(要自己设置文件夹,方便管理,不然文件添乱不方便管理) 3.注意,脚本的名字一旦确定就不要去改动,因为 ...