mybatis分页
时间: 2023-06-30 10:21:05 浏览: 43
MyBatis 提供了两种分页方式:基于拦截器(Interceptor)和基于插件(Plugin)。
基于拦截器的分页方式是直接在 SQL 语句中添加分页参数,然后使用拦截器进行拦截和处理。这种方式的优点是简单易用,缺点是需要手动拼接 SQL 语句,不够灵活。
基于插件的分页方式是开发一个 MyBatis 插件,在查询语句执行前拦截并修改查询语句,实现分页功能。这种方式的优点是可以灵活地处理各种分页需求,缺点是需要开发插件,相对比较复杂。
以下是基于拦截器的分页示例:
1. 在 MyBatis 配置文件中添加拦截器:
```xml
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
```
2. 在查询语句中添加分页参数:
```xml
<select id="getUserList" resultType="User">
select * from user
<where>
<if test="name != null">
and name like concat('%', #{name}, '%')
</if>
</where>
order by id desc
limit #{start}, #{pageSize}
</select>
```
其中 start 和 pageSize 是分页参数,可以在 Java 代码中动态设置。PageHelper 是一个开源的 MyBatis 分页插件,可以轻松实现基于拦截器的分页功能。