preface
the paging function is often used in the development of Java projects. Now SpringBoot is widely used for rapid development, and the data layer mainly integrates two frameworks, SpringDataJPA and MyBatis. Both frameworks provide corresponding paging tools and the use method is very simple. In addition, I also use the third more convenient and flexible paging method in my work, Here to share with you.
use
It is mainly divided into spring data JPA paging, MyBatis paging and Hutools tool class paging
1. Spring data JPA paging
1) . introducing dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2) Write paging Service in Service
SpringDataJPA paging is to define Pageable objects to handle paging, in which PageRequest defines paging parameters, and Page objects take over the query results for paging packaging. The packaged results pageResult can get the total records, total pages, paging list and other data results.
/** * Query all attention lists according to doctorId [pagination] * * @param doctorId Doctor id * @return Result set */ public Map<String, Object> findAllListByDoctorId(Long doctorId, Integer pageIndex, Integer pageSize) { Pageable pageable = PageRequest.of(pageIndex - 1, pageSize); // paging Page<Follow> pageResult = followRepository.findByDoctorIdOrderByCreatedAtDesc(doctorId, pageable); List<FollowDTO> dtoList = followMapper.toDto(pageResult.getContent()); if (!CollectionUtils.isEmpty(dtoList)) { // Processing business logic } // Encapsulate paging results Map<String, Object> map = new HashMap<>(); map.put("pageIndex", pageIndex.toString()); // Current page map.put("pageSize", pageSize.toString()); // Number of entries per page map.put("total", Long.toString(pageResult.getTotalElements())); // Total records map.put("pages", Integer.toString(pageResult.getTotalPages())); // PageCount map.put("list", dtoList); // Data list return map; }
3) Dealing with paging in the Repository
here is to inherit the JpaRepository object, then pass in the pageable object defined in the service, and return the result wrapped in Page.
import com.patient.domain.Follow; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; @Repository public interface FollowRepository extends JpaRepository<Follow, Long> { Page<Follow> findByDoctorIdOrderByCreatedAtDesc(Long doctorId, Pageable pageable); }
2. MyBatis paging
1) . introduce PageHelper dependency
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> </dependency>
2) Use PageHelper to realize paging
/** * Query the list of promoters, pagination. * @return Encapsulated paging result object */ public PageResult findPromotePersonList(String hospitalCode,PromotePersonReq promotePersonReq) { Integer pageIndex = promotePersonReq.getPageIndex(); Integer pageSize = promotePersonReq.getPageSize(); PageHelper.startPage(pageIndex, pageSize); // The size of each page is pageSize. Query the results of page List<PromotePerson> list = promotePersonMapper.selectAll(); PageInfo<PromotePerson> pageInfo = new PageInfo<>(list); PageHelper.clearPage(); // Return paging results PageResult pageResult = new PageResult(); pageResult.setPageIndex(pageIndex); pageResult.setPageSize(pageSize); pageResult.setPages(pageInfo.getPages()); pageResult.setTotal((int) pageInfo.getTotal()); pageResult.setList(list); return pageResult; }
3. Hutools tool class paging
1) . introducing dependency
here are some tools that can be introduced separately. For details, please refer to the official website documents. I will use this tool when writing projects, so I directly introduced all tools.
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.1.2</version> </dependency>
2) . paging implementation
two tool classes are generally used, one is pageutil Totalpage (total records, records per page) to calculate the total number of pages. The second is collatil Page (index, number of records per page, data list) to return the specified paging results. Note that the index here starts from 1, which is different from the spring data JPA paging index starting from 0.
/** * My order - to be paid [pagination] * * @param openid User unique ID * @return Result set */ public Map<String, Object> findMyOrderNotPay(String openid, Integer pageIndex, Integer pageSize) { Map<String, Object> map = new HashMap<>(); // query List<ConsultOrder> orderList = consultOrderRepository.findMyOrderNotPay(openid); if (CollectionUtils.isEmpty(orderList)) { map.put("pageIndex", pageIndex.toString()); // Current page map.put("pageSize", pageSize.toString()); // Number of entries per page map.put("total", "0"); // Total records map.put("pages", "0"); // PageCount map.put("list", new ArrayList<>()); // Data list return map; } List<OrderVO> pageList = new ArrayList<>(); int totalSize = 0; int totalPage = 0; // Calculate total pages totalSize = orderList.size(); totalPage = PageUtil.totalPage(totalSize, pageSize); // Pagination. Only when the index is less than or equal to the total number of pages can the list be returned if (pageIndex <= totalPage) { // paging pageList = CollUtil.page(pageIndex, pageSize, orderVOList); } // Return results map.put("pageIndex", Integer.toString(pageIndex)); // Current page map.put("pageSize", Integer.toString(pageSize)); // Number of entries per page map.put("total", Integer.toString(totalSize)); // Total records map.put("pages", Integer.toString(totalPage)); // PageCount map.put("list", pageList); // Data list return map; }
summary
1). Note: in order to facilitate the demonstration code to directly use the Map object to wrap the returned paging results, in the actual project, remember to define the entity object as the return result, because if the result returned by the Map object is a dynamic list with a large amount of data, there is a risk of memory leakage. For example, For example, when 10 paging records of interrogation are returned, the attribute of chat content contains a lot of chat data, because you can't determine how much the two people talked, but it is indeed included in the paging record as an attribute;
2). Spring datajpa paging is handled by using the built-in Pageable object. It should be noted that the paging index starts from 0. If it is mistransmitted, the paging results will be disordered or repeated;
3). Mybatis paging is realized with the help of PageHelper tool, PageHelper Startpage and PageHelper In the middle of clearpage is the business query code that needs paging. It can be wrapped by PageInfo object to obtain the paging parameters required and return them to the front-end display;
4). Hutools paging is to introduce hutools tool classes and implement them using PageUtil and collatil tool classes. I personally prefer this method, because in more complex query services, the first two are difficult to implement and easy to write wrong. It may not only involve multiple classes and methods, but also be difficult to read after writing for a period of time. Hutools paging is similar to the paging method long ago. I understand it as green simple JSP paging. Just use a tool paging in the service layer. It is flexible and easy to read. It is simply an artifact of paging.
my articles have always been written by hand, and they all come from the experience and sharing in practical work. If you feel that there is a bit of help, please point out a recommendation! (o..o)~