在使用 MyBatis-Plus 进行分页查询时,很多开发者会遇到一个常见的问题:当分页查询接口返回值定义为 Page<T>
时,执行查询会抛出异常;而将返回值修改为 IPage<T>
时,分页查询却能正常工作。本文将从 MyBatis-Plus 的分页机制入手,详细分析这一问题的根源,并提供相应的解决方案。
一、问题现象描述
在 MyBatis-Plus 中,我们通常会定义一个分页查询接口,如下:
Page<CommentsEntity> selectComments(IPage<CommentsEntity> page, @Param("args") CommentsPageArgs args);
当返回值为 Page<CommentsEntity>
时,执行分页查询会抛出如下异常:
Expected one result (or null) to be returned by selectOne(), but found: 10
但是,如果将返回值修改为 IPage<CommentsEntity>
,分页查询便能够正常执行。例如:
IPage<CommentsEntity> selectComments(IPage<CommentsEntity> page, @Param("args") CommentsPageArgs args);
这种现象让很多开发者感到困惑:Page<T>
不是继承自 IPage<T>
吗?为什么二者作为返回值时的表现却截然不同?
二、MyBatis-Plus 分页机制简析
要解答这个问题,我们首先需要了解 MyBatis-Plus 的分页机制。
-
分页插件
MyBatis-Plus 通过分页插件(如PaginationInterceptor
或MybatisPlusInterceptor
)来实现分页功能。在执行分页查询时,插件会拦截 SQL,并根据分页参数(如当前页码、每页大小)动态生成带LIMIT
的查询语句。 -
分页查询的返