zoukankan      html  css  js  c++  java
  • 【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现

    一.不带有动态条件的查询 分页的实现

     实例代码:

    controller:返回的是Page<>对象

    1. @Controller  
    2. @RequestMapping(value = "/egg")  
    3. public class EggController {  
    4.  @ResponseBody  
    5.     @RequestMapping(value = "/statisticsList")  
    6.     public Page<StatisticsDto> statisticsList(@RequestParam("actId") Long actId,HttpServletRequest request,  
    7.                                               Pageable pageable){  
    8.         Long entId = CasUtils.getEntId(request);  
    9.         return eggService.findStatisticsWithPage(entId,actId,pageable) ;  
    10.     }  
    11. }  

    serviceImpl中的实现方法:这里需要查询出数据的数量total,以及查询到的数据list,最后new一个实现类 new PageImpl(list,pageable,total)

                        Page 的实现类是PageImpl          Pageable 的实现类是PagerRequest

    1.     public Page<StatisticsDto> findStatisticsWithPage(Long entId, Long actId, Pageable pageable) {  
    2.         int total = wactPlayRecordDao.findDistinctPlayRecordTotal(entId, actId);  
    3. //        List<String> openIdList = wactPlayRecordDao.findDistinctPlayRecordList(entId, actId);  
    4.         List<WactPlayRecord> wactPlayRecordList = wactPlayRecordDao.findDistinctPlayRecordList(entId,actId);  
    5.         List<StatisticsDto> statisticsDtoList = new ArrayList<>();  
    6.         if (wactPlayRecordList.size()>0){  
    7. //            statisticsDtoList = new ArrayList<>(wactPlayRecordList.size());  
    8.             for (WactPlayRecord wactPlayRecord:wactPlayRecordList){  
    9.                 StatisticsDto statisticsDto = new StatisticsDto();  
    10.                 String openid = wactPlayRecord.getOpenid();  
    11.                 Long playRecordId = wactPlayRecord.getId();  
    12.                 Mpuser mpuser = mpuserDao.findMpUserByOpenId(openid);  
    13.                 List<CustomerCollItemInfo> customerCollItemInfoList = customerCollitemInfoDao.findCustomerCollItemInfoByOpenId(openid,entId,actId,playRecordId);  
    14.                 List<CustCollItemsInfoDto> custCollItemsInfoDtoList = new ArrayList<>();  
    15.                 if (customerCollItemInfoList.size()>0){  
    16.                     statisticsDto.setDetailIsShow("able");  
    17.                     custCollItemsInfoDtoList = new ArrayList<>(customerCollItemInfoList.size());  
    18.                     for (CustomerCollItemInfo customerCollItemInfo:customerCollItemInfoList){  
    19.                         CustCollItemsInfoDto custCollItemsInfoDto = new CustCollItemsInfoDto(customerCollItemInfo);  
    20.                         custCollItemsInfoDtoList.add(custCollItemsInfoDto);  
    21.                     }  
    22.                 }else{  
    23.                     //已中奖但是未填写&&未中奖  
    24.                     statisticsDto.setDetailIsShow("unable");  
    25.                 }  
    26.                 if (wactPlayRecord.getIsWin()==0){  
    27.                     wactPlayRecord.setIsUse(2);  
    28.                 }  
    29.                 WactPlayRecordDto wactPlayRecordDto = new WactPlayRecordDto(wactPlayRecord);  
    30.                 MpuserDto mpuserDto = null;  
    31.                 if (mpuser!= null){  
    32.                     mpuserDto = new MpuserDto(mpuser);  
    33.                 }  
    34.                 statisticsDto.setWactPlayRecordDto(wactPlayRecordDto);  
    35.                 statisticsDto.setCustCollItemsInfoDtoList(custCollItemsInfoDtoList);  
    36.                 statisticsDto.setMpuserDto(mpuserDto);  
    37.   
    38.                 statisticsDtoList.add(statisticsDto);  
    39.             }  
    40.         }  
    41.         return new PageImpl(statisticsDtoList,pageable,total);  
    42.     }  


    dao:需要继承JpaRepository

    1. public interface WactPlayRecordDao extends JpaRepository<WactPlayRecord, Long>{  
    2.   
    3.   
    4.  @Query("FROM WactPlayRecord w WHERE w.entId = :endId AND w.actId = :actId AND w.status = 1")  
    5.     List<WactPlayRecord> findDistinctPlayRecordList(@Param("endId") Long endId,@Param("actId") Long actId);  
    6. <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")  
    7.     int findDistinctPlayRecordTotal(@Param("endId") Long endId,@Param("actId") Long actId);  


    }

    二。带有查询条件,两种方法

        方式1(使用与查询条件在一个实体类中).:

           controller:同样是返回的Page<>对象 ,增加了表单提交的数据对象

    1. @Controller  
    2. @RequestMapping("/news")  
    3. public class NewsController {  
    4.     private NewsService newsService;  
    5.     private NewsCategoryService newsCategoryService;  
    1. @RequestMapping("/list")  
    2. @ResponseBody  
    3. public Page<NewsDto> list(Pageable pageable, NewsCondition newsCondition) {  
    4.     Long id = AppUtils.getBean("loginInfo", LoginInfo.class).getEntId();  
    5.     newsCondition.setEntId(id);  
    6.     return newsService.find(newsCondition, pageable);  
    7. }  


        serviceImpl

    1. @Service  
    2. public class NewsServiceImpl implements NewsService {  
    3. @Override  
    4.     @Transactional(readOnly = true)  
    5.     public Page<NewsDto> find(final NewsCondition condition, Pageable pageable) {  
    6.         Page<NewsEntity> page = newsDao.findAll(new Specification<NewsEntity>() {  
    7.             @Override  
    8.             public Predicate toPredicate(Root<NewsEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {  
    9.                 List<Predicate> list = new ArrayList<>();  
    10.                 list.add(cb.equal(root.get("entId").as(Long.class), condition.getEntId()));  
    11.                 list.add(cb.equal(root.get("deleted").as(Boolean.class), false));  
    12.                 Join<NewsEntity, NewsCategoryEntity> newsCategoryJoin = root.join("newsCategory");  
    13.                 list.add(cb.equal(newsCategoryJoin.get("enable").as(Boolean.class), true));  
    14.                 list.add(cb.equal(newsCategoryJoin.get("deleted").as(Boolean.class), false));  
    15.                 if (condition.getCategoryId() != null) {  
    16.                     list.add(cb.equal(newsCategoryJoin.get("id").as(Long.class), condition.getCategoryId()));  
    17.                 }  
    18.                 if (StringUtils.isNotBlank(condition.getTitle())) {  
    19.                     list.add(cb.like(root.get("title").as(String.class), "%" + condition.getTitle() + "%"));  
    20.                 }  
    21.                 if (condition.getFromDate() != null) {  
    22.                     list.add(cb.greaterThanOrEqualTo(root.get("createdDate").as(Date.class), DateUtils.getDateWithStartSecond(condition.getFromDate())));  
    23.                 }  
    24.                 if (condition.getToDate() != null) {  
    25.                     list.add(cb.lessThanOrEqualTo(root.get("createdDate").as(Date.class), DateUtils.getDateWithLastSecond(condition.getToDate())));  
    26.                 }  
    27.                 query.orderBy(cb.desc(root.get("top")), cb.desc(root.get("id")));  
    28.                 Predicate[] predicates = new Predicate[list.size()];  
    29.                 predicates = list.toArray(predicates);  
    30.                 return cb.and(predicates);  
    31.             }  
    32.         }, pageable);  
    33.   
    34.         if (page.hasContent()) {  
    35.             List<NewsEntity> newsEntities = page.getContent();  
    36.             List<NewsDto> newsDtos = new ArrayList<>(newsEntities.size());  
    37.             List<Long> pids = new ArrayList<>();  
    38.             for (NewsEntity newsEntity : newsEntities) {  
    39.                 if (newsEntity.getTitleImage() != null) {  
    40.                     pids.add(newsEntity.getTitleImage());  
    41.                 }  
    42.             }  
    43.             Map<Long, MediaFileEntity> map = null;  
    44.             if (CollectionUtils.isNotEmpty(pids)) {  
    45.                 map = mediaFileDao.findWithMap(pids);  
    46.             }  
    47.             for (NewsEntity newsEntity : newsEntities) {  
    48.                 newsDtos.add(new NewsDto(newsEntity, map != null ? map.get(newsEntity.getTitleImage()) : null));  
    49.             }  
    50.             return new PageImpl(newsDtos, pageable, page.getTotalElements());  
    51.         }  
    52.         return null;  
    53.     }  
    54. }  

    dao:这里一定要继承JpasSpecificationExecutor,然后使用其中的findAll()方法,其中封装了分页方法,排序方法等

    1. public interface NewsDao extends JpaRepository<NewsEntity, Long>, JpaSpecificationExecutor<NewsEntity> {  
    2.   
    3.  }  


      方式二(查询条件在不同表中的情形):底层DAO使用sql拼装,service中仍然使用new PageImpl的方法

          controller

       

    1. @Controller  
    2. @RequestMapping(value = "/egg")  
    3. public class EggController {  
    4.   
    5.   
    6.     @ResponseBody  
    7.     @RequestMapping(value = "/statisticsList")  
    8.     public Page<StatisticsDto> statisticsList(@RequestParam("actId") Long actId,HttpServletRequest request,  
    9.                                               Pageable pageable,StatisticsCondition statisticsCondition){  
    10.         Long entId = CasUtils.getEntId(request);  
    11.         return eggService.findStatisticsWithPage(entId,actId,pageable,statisticsCondition) ;  
    12.     }  



    serviceImpl

    1.     @Override  
    2.     @Transactional  
    3.     public Page<StatisticsDto> findStatisticsWithPage(Long entId, Long actId, Pageable pageable, StatisticsCondition statisticsCondition) {  
    4.         Long total = wactPlayRecordDao.findTotalByCondition(entId,actId,  
    5.                 statisticsCondition.getParticipateBegin(),statisticsCondition.getParticipateEnd()  
    6.                 ,statisticsCondition.getTelephone(),statisticsCondition.getIsWin(),statisticsCondition.getIsUse());  
    7.         List<StatisticsDto> statisticsDtoList = new ArrayList<>();  
    8.         if (total >0){  
    9.             List<Object[]> objectList = wactPlayRecordDao.findStatisticsByConditionWithPage(entId,actId,  
    10.                     statisticsCondition.getParticipateBegin(),statisticsCondition.getParticipateEnd()  
    11.                     ,statisticsCondition.getTelephone(),statisticsCondition.getIsWin(),statisticsCondition.getIsUse(),pageable);  
    12.             for (Object[] obj:objectList){  
    13.                 StatisticsDto statisticsDto = new StatisticsDto();  
    14.                 Long id = new BigInteger(obj[0].toString()).longValue();  
    15.                 Integer isWin = new Short(obj[1].toString()).intValue();  
    16.                 Integer isUse = new Short(obj[2].toString()).intValue();  
    17.                 String createdDateStr = com.raipeng.micro.core.utils.DateUtils.format((Date)obj[4], com.raipeng.micro.core.utils.DateUtils.PATTERN_2);  
    18.                 WactAwards wactAwards = new WactAwards();  
    19.                 Long awardsId = new BigInteger(obj[5].toString()).longValue();  
    20.                 if (awardsId != 0l){  
    21.                     wactAwards = wactAwardsDao.findAwardByAwardId(awardsId);  
    22.                 }  
    23.                 if (isWin == 0){  
    24.                     isUse = 2;  
    25.                 }  
    26.   
    27.                 WactPlayRecordDto wactPlayRecordDto = new WactPlayRecordDto(id,isWin,isUse,(String)obj[3],wactAwards.getName(),wactAwards.getGradeName(),createdDateStr);  
    28.   
    29.                 String openid = (String)obj[3];  
    30.                 Long playRecordId = wactPlayRecordDto.getId();  
    31.                 List<CustomerCollItemInfo> customerCollItemInfoList = customerCollitemInfoDao.findCustomerCollItemInfoByPlayRecordId(playRecordId);  
    32.                 List<CustCollItemsInfoDto> custCollItemsInfoDtoList = new ArrayList<>();  
    33.                 if (customerCollItemInfoList.size()>0){  
    34.                     statisticsDto.setDetailIsShow("able");  
    35.                     custCollItemsInfoDtoList = new ArrayList<>(customerCollItemInfoList.size());  
    36.                     for (CustomerCollItemInfo customerCollItemInfo:customerCollItemInfoList){  
    37. //                        customerCollItemsIds +=customerCollItemInfo.getCustomerCollectitemsId()+"#";  
    38.                         CustCollItemsInfoDto custCollItemsInfoDto = new CustCollItemsInfoDto(customerCollItemInfo);  
    39.                         custCollItemsInfoDtoList.add(custCollItemsInfoDto);  
    40.                     }  
    41.                 }else{  
    42.                     //已中奖但是未填写&&未中奖  
    43.                     statisticsDto.setDetailIsShow("unable");  
    44.                 }  
    45.   
    46.                 Object[] object = wactPlayRecordDao.findUserInfoByOpenId(openid);  
    47.                 MpuserDto mpuserDto = new MpuserDto();  
    48.                 if (object[1] != null){  
    49.                     mpuserDto.setHeadImg((String)object[1]);  
    50.                 }else if (object[3] != null){  
    51.                     mpuserDto.setHeadImg((String)object[3]);  
    52.                 }else {  
    53.                     mpuserDto.setHeadImg("");  
    54.                 }  
    55.                 if (object[2] != null){  
    56.                     mpuserDto.setNickName((String)object[2]);  
    57.                 }else if (object[4] != null){  
    58.                     mpuserDto.setNickName((String)object[4]);  
    59.                 }else {  
    60.                     mpuserDto.setNickName("");  
    61.                 }  
    62.                 if (wactPlayRecordDto.getIsWin()=="已中奖" && custCollItemsInfoDtoList.size()==0){  
    63.                     wactPlayRecordDto.setIsUse("");  
    64.                 }  
    65.                 if (mpuserDto.getHeadImg()==""){  
    66.                     statisticsDto.setHeadImg("unable");  
    67.                 }else{  
    68.                     statisticsDto.setHeadImg("able");  
    69.                 }  
    70.                 if (wactPlayRecordDto.getIsUse()=="已领取"){  
    71.                     statisticsDto.setHaveReceived("able");  
    72.                 }else {  
    73.                     statisticsDto.setHaveReceived("unable");  
    74.                 }  
    75.                 statisticsDto.setWactPlayRecordDto(wactPlayRecordDto);  
    76.                 statisticsDto.setCustCollItemsInfoDtoList(custCollItemsInfoDtoList);  
    77.                 statisticsDto.setMpuserDto(mpuserDto);  
    78.                 if (wactPlayRecordDto.getIsUse()=="未领取"){  
    79.                     statisticsDto.setSetReceive("able");  
    80.                 }else {  
    81.                     statisticsDto.setSetReceive("unable");  
    82.                 }  
    83.   
    84.                 String customerCollItemsIds = "";  
    85.                 List<CustomerCollectItems> customerCollectItemsList = customerCollectItemsDao.findListByActivityId(actId);  
    86.                 if (customerCollectItemsList != null && customerCollectItemsList.size()>0){  
    87.                     for (CustomerCollectItems customerCollectItems:customerCollectItemsList){  
    88.                         customerCollItemsIds += customerCollectItems.getCollectItemsId()+"#";  
    89.                     }  
    90.                 }  
    91.                 statisticsDto.setCustomerCollectItemsIds(customerCollItemsIds);  
    92.                 statisticsDtoList.add(statisticsDto);  
    93.             }  
    94.         }  
    95.   
    96.         return new PageImpl<StatisticsDto>(statisticsDtoList,pageable,total);  
    97.     }  

    dao   daoplus  daoImpl(dao继承daoPlus,daoImpl实现daoPlus)

    daoplus

    1. public interface WactPlayRecordPlusDao {  
    2.  Long findTotalByCondition(Long entId,Long actId,Date participateBegin,Date participateEnd,String telephone,Integer isWin,Integer isUse);  
    3.   
    4. List<Object[]> findStatisticsByConditionWithPage(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse,Pageable pageable);  
    5. }  

    daoImpl

      1. public class WactPlayRecordDaoImpl implements WactPlayRecordPlusDao {  
      2. @PersistenceContext  
      3.     private EntityManager entityManager;  
      4.   
      5.     public void setEntityManager(EntityManager entityManager) {  
      6.         this.entityManager = entityManager;  
      7.     }  
      8.   
      9.     @Override  
      10.     public Long findTotalByCondition(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse) {  
      11.         StringBuffer sql = null;  
      12.         if (telephone != null && !"".equals(telephone)){  
      13. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,W.openid " +//表没有关联所以不能使用面向对象语句的left outer join inner join 等  
      14. //                    "FROM WactPlayRecord w inner join CustomerCollItemInfo c " +  
      15. //                    "ON w.id = c.playRecordId" +  
      16. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " +  
      17. //                    "AND c.entId = :entId AND c.actId = :actId AND c.status = 1 And c.val = :telephone ");  
      18.             sql =new StringBuffer("SELECT count(p.id)" +  
      19.                     "FROM rp_act_play_record p inner join rp_act_customer_collitem_info c " +  
      20.                     "ON p.id = c.play_record_id " +  
      21.                     "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " +  
      22.                     "AND c.ent_id = :entId AND c.act_id = :actId AND c.status = 1 And c.val = :telephone ");  
      23.         }else {  
      24. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,w.openid " +  
      25. //                    "FROM WactPlayRecord w " +  
      26. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " );  
      27.             sql = new StringBuffer("SELECT count(p.id) " +  
      28.                     "FROM rp_act_play_record p " +  
      29.                     "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " );  
      30.         }  
      31.         if (participateBegin != null){  
      32.             sql.append("AND p.created_date >= :participateBegin ");  
      33.         }  
      34.         if (participateEnd != null){  
      35.             sql.append("AND p.created_date <= :participateEnd ");  
      36.         }  
      37.         if (isWin == 0){  
      38.             sql.append("AND p.is_win = 0 ");  
      39.         }else if (isWin ==1){  
      40.             sql.append("AND p.is_win = 1 ");  
      41.         }  
      42.         if (isUse == 0){  
      43.             sql.append("AND p.is_use = 0 ");  
      44.         }else if (isUse == 1){  
      45.             sql.append("AND p.is_use = 1 ");  
      46.         }  
      47.         sql.append("order by p.created_date ASC");  
      48.         Query query = entityManager.createNativeQuery(sql.toString());  
      49.         query.setParameter("entId", entId).setParameter("actId", actId);  
      50.         if (participateBegin != null){  
      51.             query.setParameter("participateBegin", participateBegin);  
      52.         }  
      53.         if (participateEnd != null){  
      54.             query.setParameter("participateEnd", participateEnd);  
      55.         }  
      56.         if (telephone != null && !"".equals(telephone)){  
      57.             query.setParameter("telephone",telephone);  
      58.         }  
      59.         Long total = new BigInteger(query.getSingleResult().toString()).longValue();  
      60.         return total;  
      61.     }  
      62.   
      63.     @Override  
      64.     public List<Object[]> findStatisticsByConditionWithPage(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse,Pageable pageable) {  
      65.         StringBuffer sql = null;  
      66.         if (telephone != null && !"".equals(telephone)){  
      67. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,W.openid " +  
      68. //                    "FROM WactPlayRecord w inner join CustomerCollItemInfo c " +  
      69. //                    "ON w.id = c.playRecordId" +  
      70. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " +  
      71. //                    "AND c.entId = :entId AND c.actId = :actId AND c.status = 1 And c.val = :telephone ");  
      72.            sql =new StringBuffer("SELECT p.id,p.is_win,p.is_use,p.openid,p.created_date,p.awards_id " +  
      73.                     "FROM rp_act_play_record p inner join rp_act_customer_collitem_info c " +  
      74.                     "ON p.id = c.play_record_id " +  
      75.                     "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " +  
      76.                     "AND c.ent_id = :entId AND c.act_id = :actId AND c.status = 1 And c.val = :telephone ");  
      77.         }else {  
      78. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,w.openid " +  
      79. //                    "FROM WactPlayRecord w " +  
      80. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " );  
      81.             sql = new StringBuffer("SELECT p.id,p.is_win,p.is_use,p.openid,p.created_date,p.awards_id " +  
      82.                     "FROM rp_act_play_record p " +  
      83.                     "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " );  
      84.         }  
      85.         if (participateBegin != null){  
      86.             sql.append("AND p.created_date >= :participateBegin ");  
      87.         }  
      88.         if (participateEnd != null){  
      89.             sql.append("AND p.created_date <= :participateEnd ");  
      90.         }  
      91.         if (isWin == 0){  
      92.             sql.append("AND p.is_win = 0 ");  
      93.         }else if (isWin ==1){  
      94.             sql.append("AND p.is_win = 1 ");  
      95.         }  
      96.         if (isUse == 0){  
      97.             sql.append("AND p.is_use = 0 ");  
      98.         }else if (isUse == 1){  
      99.             sql.append("AND p.is_use = 1 ");  
      100.         }  
      101.         sql.append("order by p.created_date DESC");  
      102.         Query query = entityManager.createNativeQuery(sql.toString());  
      103.         query.setParameter("entId", entId).setParameter("actId", actId);  
      104.         if (participateBegin != null){  
      105.             query.setParameter("participateBegin", participateBegin);  
      106.         }  
      107.         if (participateEnd != null){  
      108.             query.setParameter("participateEnd", participateEnd);  
      109.         }  
      110.         if (telephone != null && !"".equals(telephone)){  
      111.             query.setParameter("telephone",telephone);  
      112.         }  
      113.         query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());  
      114.         query.setMaxResults(pageable.getPageSize());  
      115.         List<Object[]> objectList = query.getResultList();  
      116.         return objectList;  
      117.     } 
  • 相关阅读:
    软件工程概论-用户登录界面
    2016.11.25异常处理
    2016.11.18多态
    2016.11.11继承与接口
    11.6数组
    10.28字符串加密等
    python 读写文件
    python可变的类型、不可变的类型
    python 字典练习 记录学生是否交作业的小程序
    python字典
  • 原文地址:https://www.cnblogs.com/gyadmin/p/8615123.html
Copyright © 2011-2022 走看看