mybatisplus 实现分页
时间: 2023-09-03 22:15:19 浏览: 98
MybatisPlus实现分页的步骤如下:
1. 引入MybatisPlus依赖
在项目的pom.xml中添加MybatisPlus的依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
```
2. 配置分页插件
在MybatisPlus的配置类中,配置分页插件:
```java
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
```
3. 使用分页查询
在需要分页查询的地方,使用MybatisPlus的Page对象进行查询:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getUserList(int page, int size) {
Page<User> userPage = new Page<>(page, size);
return userMapper.selectPage(userPage, null).getRecords();
}
}
```
其中,Page的第一个参数为当前页数,第二个参数为每页大小。selectPage方法的第一个参数为Page对象,第二个参数为查询条件。getRecords()方法获取查询结果。
4. 返回分页信息
可以在返回结果中,添加分页信息:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageResult<User> getUserList(int page, int size) {
Page<User> userPage = new Page<>(page, size);
userMapper.selectPage(userPage, null);
return new PageResult<>(userPage);
}
}
```
其中,PageResult包含了查询结果和分页信息。在构造函数中,传入Page对象即可获取分页信息。
阅读全文
相关推荐

















