【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现

时间:2023-03-09 13:28:47
【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. statisticsDtoList.add(statisticsDto);
  38. }
  39. }
  40. return new PageImpl(statisticsDtoList,pageable,total);
  41. }

dao:需要继承JpaRepository

  1. public interface WactPlayRecordDao extends JpaRepository<WactPlayRecord, Long>{
  2. @Query("FROM WactPlayRecord w WHERE w.entId = :endId AND w.actId = :actId AND w.status = 1")
  3. List<WactPlayRecord> findDistinctPlayRecordList(@Param("endId") Long endId,@Param("actId") Long actId);
  4. <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")
  5. 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. if (page.hasContent()) {
  34. List<NewsEntity> newsEntities = page.getContent();
  35. List<NewsDto> newsDtos = new ArrayList<>(newsEntities.size());
  36. List<Long> pids = new ArrayList<>();
  37. for (NewsEntity newsEntity : newsEntities) {
  38. if (newsEntity.getTitleImage() != null) {
  39. pids.add(newsEntity.getTitleImage());
  40. }
  41. }
  42. Map<Long, MediaFileEntity> map = null;
  43. if (CollectionUtils.isNotEmpty(pids)) {
  44. map = mediaFileDao.findWithMap(pids);
  45. }
  46. for (NewsEntity newsEntity : newsEntities) {
  47. newsDtos.add(new NewsDto(newsEntity, map != null ? map.get(newsEntity.getTitleImage()) : null));
  48. }
  49. return new PageImpl(newsDtos, pageable, page.getTotalElements());
  50. }
  51. return null;
  52. }
  53. }

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

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

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

controller

  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,StatisticsCondition statisticsCondition){
  8. Long entId = CasUtils.getEntId(request);
  9. return eggService.findStatisticsWithPage(entId,actId,pageable,statisticsCondition) ;
  10. }

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. WactPlayRecordDto wactPlayRecordDto = new WactPlayRecordDto(id,isWin,isUse,(String)obj[3],wactAwards.getName(),wactAwards.getGradeName(),createdDateStr);
  27. String openid = (String)obj[3];
  28. Long playRecordId = wactPlayRecordDto.getId();
  29. List<CustomerCollItemInfo> customerCollItemInfoList = customerCollitemInfoDao.findCustomerCollItemInfoByPlayRecordId(playRecordId);
  30. List<CustCollItemsInfoDto> custCollItemsInfoDtoList = new ArrayList<>();
  31. if (customerCollItemInfoList.size()>0){
  32. statisticsDto.setDetailIsShow("able");
  33. custCollItemsInfoDtoList = new ArrayList<>(customerCollItemInfoList.size());
  34. for (CustomerCollItemInfo customerCollItemInfo:customerCollItemInfoList){
  35. //                        customerCollItemsIds +=customerCollItemInfo.getCustomerCollectitemsId()+"#";
  36. CustCollItemsInfoDto custCollItemsInfoDto = new CustCollItemsInfoDto(customerCollItemInfo);
  37. custCollItemsInfoDtoList.add(custCollItemsInfoDto);
  38. }
  39. }else{
  40. //已中奖但是未填写&&未中奖
  41. statisticsDto.setDetailIsShow("unable");
  42. }
  43. Object[] object = wactPlayRecordDao.findUserInfoByOpenId(openid);
  44. MpuserDto mpuserDto = new MpuserDto();
  45. if (object[1] != null){
  46. mpuserDto.setHeadImg((String)object[1]);
  47. }else if (object[3] != null){
  48. mpuserDto.setHeadImg((String)object[3]);
  49. }else {
  50. mpuserDto.setHeadImg("");
  51. }
  52. if (object[2] != null){
  53. mpuserDto.setNickName((String)object[2]);
  54. }else if (object[4] != null){
  55. mpuserDto.setNickName((String)object[4]);
  56. }else {
  57. mpuserDto.setNickName("");
  58. }
  59. if (wactPlayRecordDto.getIsWin()=="已中奖" && custCollItemsInfoDtoList.size()==0){
  60. wactPlayRecordDto.setIsUse("");
  61. }
  62. if (mpuserDto.getHeadImg()==""){
  63. statisticsDto.setHeadImg("unable");
  64. }else{
  65. statisticsDto.setHeadImg("able");
  66. }
  67. if (wactPlayRecordDto.getIsUse()=="已领取"){
  68. statisticsDto.setHaveReceived("able");
  69. }else {
  70. statisticsDto.setHaveReceived("unable");
  71. }
  72. statisticsDto.setWactPlayRecordDto(wactPlayRecordDto);
  73. statisticsDto.setCustCollItemsInfoDtoList(custCollItemsInfoDtoList);
  74. statisticsDto.setMpuserDto(mpuserDto);
  75. if (wactPlayRecordDto.getIsUse()=="未领取"){
  76. statisticsDto.setSetReceive("able");
  77. }else {
  78. statisticsDto.setSetReceive("unable");
  79. }
  80. String customerCollItemsIds = "";
  81. List<CustomerCollectItems> customerCollectItemsList = customerCollectItemsDao.findListByActivityId(actId);
  82. if (customerCollectItemsList != null && customerCollectItemsList.size()>0){
  83. for (CustomerCollectItems customerCollectItems:customerCollectItemsList){
  84. customerCollItemsIds += customerCollectItems.getCollectItemsId()+"#";
  85. }
  86. }
  87. statisticsDto.setCustomerCollectItemsIds(customerCollItemsIds);
  88. statisticsDtoList.add(statisticsDto);
  89. }
  90. }
  91. return new PageImpl<StatisticsDto>(statisticsDtoList,pageable,total);
  92. }

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. List<Object[]> findStatisticsByConditionWithPage(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse,Pageable pageable);
  4. }

daoImpl

    1. public class WactPlayRecordDaoImpl implements WactPlayRecordPlusDao {
    2. @PersistenceContext
    3. private EntityManager entityManager;
    4. public void setEntityManager(EntityManager entityManager) {
    5. this.entityManager = entityManager;
    6. }
    7. @Override
    8. public Long findTotalByCondition(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse) {
    9. StringBuffer sql = null;
    10. if (telephone != null && !"".equals(telephone)){
    11. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,W.openid " +//表没有关联所以不能使用面向对象语句的left outer join inner join 等
    12. //                    "FROM WactPlayRecord w inner join CustomerCollItemInfo c " +
    13. //                    "ON w.id = c.playRecordId" +
    14. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " +
    15. //                    "AND c.entId = :entId AND c.actId = :actId AND c.status = 1 And c.val = :telephone ");
    16. sql =new StringBuffer("SELECT count(p.id)" +
    17. "FROM rp_act_play_record p inner join rp_act_customer_collitem_info c " +
    18. "ON p.id = c.play_record_id " +
    19. "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " +
    20. "AND c.ent_id = :entId AND c.act_id = :actId AND c.status = 1 And c.val = :telephone ");
    21. }else {
    22. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,w.openid " +
    23. //                    "FROM WactPlayRecord w " +
    24. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " );
    25. sql = new StringBuffer("SELECT count(p.id) " +
    26. "FROM rp_act_play_record p " +
    27. "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " );
    28. }
    29. if (participateBegin != null){
    30. sql.append("AND p.created_date >= :participateBegin ");
    31. }
    32. if (participateEnd != null){
    33. sql.append("AND p.created_date <= :participateEnd ");
    34. }
    35. if (isWin == 0){
    36. sql.append("AND p.is_win = 0 ");
    37. }else if (isWin ==1){
    38. sql.append("AND p.is_win = 1 ");
    39. }
    40. if (isUse == 0){
    41. sql.append("AND p.is_use = 0 ");
    42. }else if (isUse == 1){
    43. sql.append("AND p.is_use = 1 ");
    44. }
    45. sql.append("order by p.created_date ASC");
    46. Query query = entityManager.createNativeQuery(sql.toString());
    47. query.setParameter("entId", entId).setParameter("actId", actId);
    48. if (participateBegin != null){
    49. query.setParameter("participateBegin", participateBegin);
    50. }
    51. if (participateEnd != null){
    52. query.setParameter("participateEnd", participateEnd);
    53. }
    54. if (telephone != null && !"".equals(telephone)){
    55. query.setParameter("telephone",telephone);
    56. }
    57. Long total = new BigInteger(query.getSingleResult().toString()).longValue();
    58. return total;
    59. }
    60. @Override
    61. public List<Object[]> findStatisticsByConditionWithPage(Long entId, Long actId, Date participateBegin, Date participateEnd, String telephone, Integer isWin, Integer isUse,Pageable pageable) {
    62. StringBuffer sql = null;
    63. if (telephone != null && !"".equals(telephone)){
    64. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,W.openid " +
    65. //                    "FROM WactPlayRecord w inner join CustomerCollItemInfo c " +
    66. //                    "ON w.id = c.playRecordId" +
    67. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " +
    68. //                    "AND c.entId = :entId AND c.actId = :actId AND c.status = 1 And c.val = :telephone ");
    69. sql =new StringBuffer("SELECT p.id,p.is_win,p.is_use,p.openid,p.created_date,p.awards_id " +
    70. "FROM rp_act_play_record p inner join rp_act_customer_collitem_info c " +
    71. "ON p.id = c.play_record_id " +
    72. "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " +
    73. "AND c.ent_id = :entId AND c.act_id = :actId AND c.status = 1 And c.val = :telephone ");
    74. }else {
    75. //            hql = new StringBuffer("SELECT w.id,w.isWin,w.isUse,w.openid " +
    76. //                    "FROM WactPlayRecord w " +
    77. //                    "WHERE w.entId = :entId AND w.actId = :actId AND w.status = 1 " );
    78. sql = new StringBuffer("SELECT p.id,p.is_win,p.is_use,p.openid,p.created_date,p.awards_id " +
    79. "FROM rp_act_play_record p " +
    80. "WHERE p.ent_id = :entId AND p.act_id = :actId AND p.status = 1 " );
    81. }
    82. if (participateBegin != null){
    83. sql.append("AND p.created_date >= :participateBegin ");
    84. }
    85. if (participateEnd != null){
    86. sql.append("AND p.created_date <= :participateEnd ");
    87. }
    88. if (isWin == 0){
    89. sql.append("AND p.is_win = 0 ");
    90. }else if (isWin ==1){
    91. sql.append("AND p.is_win = 1 ");
    92. }
    93. if (isUse == 0){
    94. sql.append("AND p.is_use = 0 ");
    95. }else if (isUse == 1){
    96. sql.append("AND p.is_use = 1 ");
    97. }
    98. sql.append("order by p.created_date DESC");
    99. Query query = entityManager.createNativeQuery(sql.toString());
    100. query.setParameter("entId", entId).setParameter("actId", actId);
    101. if (participateBegin != null){
    102. query.setParameter("participateBegin", participateBegin);
    103. }
    104. if (participateEnd != null){
    105. query.setParameter("participateEnd", participateEnd);
    106. }
    107. if (telephone != null && !"".equals(telephone)){
    108. query.setParameter("telephone",telephone);
    109. }
    110. query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
    111. query.setMaxResults(pageable.getPageSize());
    112. List<Object[]> objectList = query.getResultList();
    113. return objectList;
    114. }