preface

Java project development often needs to use the paging function, now the widespread use of SpringBoot for rapid development, and the data layer is mainly integrated SpringDataJPA and MyBatis two frameworks, these two frameworks provide the corresponding paging tools, the use is also very simple, But I also use a third more convenient and flexible way of paging in my work, which I share with you here.




use

It is mainly divided into SpringDataJPA paging, MyBatis paging and Hutools tool class paging


1. SpringDataJPA paging

1) Introduce dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Copy the code

2) Write the paging Service in the Service

SpringDataJPA paging is to define Pageable object to handle paging, in which PageRequest defines paging parameters, Page object to take over the query results for paging packaging, the result pageResult can get the total number of records, total number of pages, paging list and other data results.

/** * select ** from doctorId@paramDoctorId Indicates the id of a doctor *@returnThe 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)) {// Process business logic....
	}
	// Encapsulate the paging result
	Map<String, Object> map = new HashMap<>();
	map.put("pageIndex", pageIndex.toString()); / / the current page
	map.put("pageSize", pageSize.toString()); // Number of entries per page
	map.put("total", Long.toString(pageResult.getTotalElements())); // Total number of records
	map.put("pages", Integer.toString(pageResult.getTotalPages())); / / the total number of pages
	map.put("list", dtoList); // Data list
	return map;
}
Copy the code

3), Repository handles paging

Inherit the JpaRepository object, pass in the Pageable object defined in the service, and return the pageable object 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);
}
Copy the code


2, MyBatis paging

1) Introduce the PageHelper dependency

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
Copy the code

2) Use PageHelper to implement pagination

/** * query the list of promoters, paging. *@returnThe 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
	List<PromotePerson> list = promotePersonMapper.selectAll();
	PageInfo<PromotePerson> pageInfo = new PageInfo<>(list);
	PageHelper.clearPage();
	// Returns 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;
}
Copy the code


3, Hutools tool class paging

1) Introduce dependencies

Please refer to the official website documents for details. I always use this tool when writing projects, so I have directly introduced all of them.

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.1.2</version>
</dependency>
Copy the code

2) paging implementation

There are usually two utility classes: pageutil. totalPage(total pages) and CollUtil. Page(index, records per page, data list) to return the results of a given page. Note that the index starts at 1. Different from SpringDataJPA paging indexes starting at 0.

/** * my order - to be paid **@paramOpenid Unique identifier *@returnThe 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()); / / the current page
            map.put("pageSize", pageSize.toString()); // Number of entries per page
            map.put("total"."0"); // Total number of records
            map.put("pages"."0"); / / the total number of pages
            map.put("list".new ArrayList<>()); // Data list
            return map;
	}
	List<OrderVO> pageList = new ArrayList<>();
	int totalSize = 0;
	int totalPage = 0;
	// Count the total pages
	totalSize = orderList.size();
        totalPage = PageUtil.totalPage(totalSize, pageSize);
	// paging, index is less than or equal to the total number of pages, return the list.
	if (pageIndex <= totalPage) {
            / / paging
            pageList = CollUtil.page(pageIndex, pageSize, orderVOList);
	}
	// Return the result
	map.put("pageIndex", Integer.toString(pageIndex)); / / the current page
	map.put("pageSize", Integer.toString(pageSize)); // Number of entries per page
	map.put("total", Integer.toString(totalSize)); // Total number of records
	map.put("pages", Integer.toString(totalPage)); / / the total number of pages
	map.put("list", pageList); // Data list
	return map;
}
Copy the code




conclusion

1) Note: For convenient demo code directly or move the Map object to wrap back page as a result, in actual project, be sure to define your own entity object as returned results, because the Map object returned result if the list is dynamic and large amount of data, there is the risk of memory leaks, for example, such as return to 10 interrogation record of paging, The chat content property contains a lot of chat data, because you can’t be sure how much two people are talking, but it does appear as a property in the paged record; 2), SpringDataJPA paging, is to use its own Pageable object to deal with, it should be noted that the paging index starts from 0, wrong transmission will cause paging results confusion or repeat phenomenon; 3), Mybatis paging, is with the help of PageHelper tool to achieve, pagehelper. startPage and pagehelper. clearPage is the middle of the need for paging business query code, can be wrapped by PageInfo object, Get the required paging parameters back to the front end display; 4) Hutools paging is the introduction of the Hutools tool class, using the PageUtil and CollUtil tool classes to implement this method, I prefer this method, because in the more complex query business, the first two methods are difficult to implement and easy to write errors, not only may involve multiple classes and methods. It’s not easy to read after a while. Hutools pagination is similar to a long time ago, I understand it as a simple green VERSION of JSP pagination, just in the service layer to use a tool class pagination, both flexible and easy to read, is simply the magic of pagination.




My article has always been pure hand dozen, and all come from the actual work experience and share, if you think there is a drop of help, click a like and collect it! (o.. o)~