SoFunction
Updated on 2025-03-08

Detailed analysis of several ways to implement pagination in Java

1. Limit keyword

Service layer

@Service
@Transactional
public class ImplStudentService implements StudentService {
@Resource
private  StudentDao  studentDao;
    @Override
    public List<Student>  selectAllStudent(String province, Integer offset, Integer limit) {
        return (province,offset,limit);
    }
}

sql statement

select * from student where province = #{province}  limit #{offset},#{limit}

2. Hibernate pagination

Service layer

  @Override
  public List getStudents(Integer  pageNo,Integer  pageSize) throws Exception {
  // Pagination data  int[] startIdAndCount = new int[2];
  startIdAndCount[0] = pageNo * pageSize;
  startIdAndCount[1] = pageSize;
  return (startIdAndCount);
 }

Dao Layer

@Override
public List findByHqlPage(int[] startIdAndCount) throws Exception {
	String hql = "...";
	try {
		Query query = getSession().createQuery(hql);
		// Set up paging		if (startIdAndCount != null &amp;&amp;  &gt; 0) {
			int rowStartIdx = (0, startIdAndCount[0]);
			if (rowStartIdx &gt; 0) {
				(rowStartIdx);// Set the index of the start value			}
			if ( &gt; 1) {
				int rowCount = (0, startIdAndCount[1]);
				if (rowCount &gt; 0) {
				(rowCount);// Set the index of the end value				}
			}
		}
		return ();
	} catch (RuntimeException re) {
		("Page query failed!", re);
		throw re;
	}
}

3. Intercept List query results pagination (simple and crude)

List<StudentEnroll> students = ();
int count = 0;
if(studentEnrolls != null && () > 0) {
	count = ();
	int fromIndex = pageNo * pageSize;
	int toIndex = (pageNo + 1) * pageSize;
	if(toIndex > count) {
		toIndex = count;
	}
	List<StudentEnroll> pageList = (fromIndex, toIndex);

4. Mybatis framework pageHelper plug-in pagination

Spring Integration:

Import

<!-- /artifact//pagehelper -->
 <dependency>
      <groupId></groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
 </dependency>

Configure project configuration file (I configured it in the configuration file integrated by spring and mybatis. If it is configured in the mybatis core configuration file, Baidu)

&lt;bean  class=""&gt;
        &lt;!-- Relying on data sources --&gt;
        &lt;property name="dataSource" ref="dataSource"/&gt;
        &lt;!-- Register to loadmyBatisMapping files --&gt;
        &lt;property name="mapperLocations"&gt;
            &lt;array&gt;
                &lt;value&gt;classpath*:com/yyz/mapper/*&lt;/value&gt;
            &lt;/array&gt;
        &lt;/property&gt;
        &lt;!-- PageHelperPagination configuration --&gt;
        &lt;property name="plugins"&gt;
            &lt;array&gt;
                &lt;bean class=""&gt;
                    &lt;property name="properties"&gt;
                        &lt;!--Use the following method to configure parameters,Configure one line,There will be all the parameters introduced later --&gt;
                        &lt;value&gt;
                    &lt;!--helperDialectProperties to specify which dialect to use for paging plugins。--&gt;
                            helperDialect=mysql
                    &lt;!--Paging rationalization parameters,Set astruehour,pageNum&lt;=0hour会查询第一页,pageNum&gt;pages(超过总数hour),Will query the last page。--&gt;
                            reasonable=true
                    &lt;!--To supportstartPage(Object params)method,This parameter has been added to configure parameter mapping,Used to take values ​​from objects based on attribute names,
                        Can be configured pageNum,pageSize,count,pageSizeZero,reasonable--&gt;
                            params=count=countSql
                    &lt;!--SupportedMapperInterface parameters to pass paging parameters,default valuefalse,分页插件会从查询method的参数值中,Automatically according to above params match
                     Take the value in the field set,查找到合适的值hour就会自动分页。--&gt;
                            supportMethodsArguments=true
                    &lt;!--default value为 false。Set as true hour,允许在运行hour根据多数据源自动识别对应方言的分页--&gt;
                            autoRuntimeDialect=true
                        &lt;/value&gt;
                    &lt;/property&gt;
                &lt;/bean&gt;
            &lt;/array&gt;
        &lt;/property&gt;
        &lt;!-- Alias ​​the database entity --&gt;
        &lt;property name="typeAliasesPackage" value=";"/&gt;
 &lt;/bean&gt;

SpringBoot integration:

&lt;!--Pagination plugin--&gt;
&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;pagehelper-spring-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;Latest version&lt;/version&gt;
&lt;/dependency&gt;

Configure project files

#bybatis paging plugin configurationpagehelper:
  helper-dialect: mysql  #database  reasonable: true
  support-methods-arguments: true
  params: count=countSql

Title paging plugin parameters:

The paging plug-in provides multiple optional parameters. When used, you can configure them according to the example in the above configuration method.

The optional parameters of the paging plug-in are as follows:

  • dialect: By default, the pageHelper method will be used for pagination. If you want to implement your own paging logic, you can implement it.Dialect() interface, and then configure the property to be the fully qualified name of the implementation class. When implementing with a custom dialect, the following parameters have no effect.
  • helperDialect: The paging plug-in will automatically detect the current database link and automatically select the appropriate paging method. oracle, mysql, mariadb, sqlite, hsqldb, postgresql, db2, sqlserver, informix, h2, sqlserver2012, derbyPay special attention: When using the SqlServer2012 database, it is necessary to manually specify it as sqlserver2012, otherwise the page will be paginated using SqlServer2005.
  • offsetAsPageNum: The default value is false, which is valid for using RowBounds as the paging parameter. When this parameter is set to true, the offset parameter in RowBounds will be used as pageNum, and you can paginate with two parameters: page number and page size.
  • rowBoundsWithCount: The default value is false, which is valid for using RowBounds as the paging parameter. When this parameter is set to true, count query is performed using the RowBounds pagination.
  • pageSizeZero: The default value is false. When this parameter is set to true, if pageSize=0 or = 0, all results will be queryed (equivalent to the fact that no paging query is performed, but the result returned is still Page type).
  • reasonable:Pagination rationalization parameter, default value is false. When this parameter is set to true, when pageNum<=0, the first page will be queryed, pageNum>pages (when the total number exceeds), the last page will be queryed. When false by default, query is directly based on the parameters.
  • params: In order to support the startPage(Object params) method, this parameter is added to configure parameter mapping. It is used to select values ​​from the object according to the attribute name. You can configure pageNum, pageSize, count, pageSizeZero, reasonable. You do not configure the default value for the mapping. The default value is pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero.
  • supportMethodsArguments: Supports passing paging parameters through Mapper interface parameters, the default value is false. The paging plug-in will automatically obtain values ​​from the parameter values ​​of the query method according to the fields configured in the params above. When the appropriate value is found, it will automatically paging.
  • aggregateFunctions: By default, it is an aggregate function for all common databases. It allows manual addition of aggregate functions (influencing the number of rows). All functions starting with an aggregate function will be covered with a layer when performing count conversion. Other functions and columns will be replaced with count(0), where the count column can be configured by itself.

Important tips:

When offsetAsPageNum=false, due to PageNum problem, reasonable will be forced to false when RowBounds query. The usage method is not affected.

Service layer

@Override
public ResponseResult selectAllStudent(Integer pageNum, Integer pageSize) {
    Map<String,Object> map = new HashMap<>();
    (pageNum,pageSize);
    List<Student>  students = ();
    PageInfo pageInfo = new PageInfo(students);
    long total = ();
    ("result",pageInfo);
    ("count",total);
    return (map);
}

5. SpringData Pagination

Service layer

 travelDate = new (, "travelDate");
 createdTime = new (, "createdTime");
Sort sort = new Sort(travelDate, createdTime);
Pageable pageable = new PageRequest(page, pageSize, sort);
List&lt;TravelItem&gt; items = null;
try {
    items = (theStartDate, theEndDate, openId, pageable);
} catch (Exception e) {
    throw new DatabaseRelatedException("TravelRepository Exception");
}

dao layer: The interface inherits the PagingAndSortingRepository interface, please add @Repository annotation

This is the end of this article about the detailed analysis of several methods of Java implementing pagination. For more related Java paging methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!