mybatis如何分页
时间: 2023-10-19 20:13:28 浏览: 84
MyBatis提供了两种分页方式:
1. 使用`RowBounds`进行分页
在`select`语句中传入`RowBounds`对象,指定起始位置和查询数量,例如:
```java
List<User> getUsers(int offset, int limit);
```
在Mapper XML中,对应的SQL语句为:
```xml
<select id="getUsers" resultMap="userMap">
select * from user
limit #{offset}, #{limit}
</select>
```
2. 使用插件进行分页
MyBatis提供了一个插件`PageHelper`,可以方便地进行分页。使用步骤如下:
1. 在`pom.xml`中添加依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
```
2. 在Mapper接口中,需要分页的方法返回类型为`PageInfo`,例如:
```java
PageInfo<User> getUsers(int pageNum, int pageSize);
```
3. 在方法执行前,调用`PageHelper.startPage()`方法进行分页设置,例如:
```java
PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.getUsers();
PageInfo<User> pageInfo = new PageInfo<>(users);
return pageInfo;
```
4. 在Mapper XML中,不需要再手动添加分页查询的语句,`PageHelper`会自动根据方法参数生成相应的SQL语句。
阅读全文
相关推荐













