SpringBoot整合MybatisPlus 实现分页查询
时间: 2024-03-21 10:33:47 浏览: 102
SpringBoot整合MybatisPlus可以很方便地实现分页查询,而MybatisPlus本身也提供了物理分页的功能。下面是实现步骤:
1.在pom.xml文件中添加MybatisPlus和分页插件的依赖。
2.在application.yml文件中配置分页插件。
3.在Mapper接口中添加分页查询方法,使用MybatisPlus提供的Page对象进行分页查询。
4.在Service层中调用Mapper接口中的分页查询方法,将查询结果封装到Page对象中返回给Controller层。
5.在Controller层中接收前端传来的分页参数,调用Service层中的分页查询方法,将查询结果返回给前端。
具体实现代码可以参考以下示例:
1.在pom.xml文件中添加MybatisPlus和分页插件的依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
2.在application.yml文件中配置分页插件:
```
mybatis-plus:
configuration:
# 开启驼峰命名转换
map-underscore-to-camel-case: true
# 配置分页插件
plugins:
- com.github.pagehelper.PageInterceptor
# 配置分页插件的参数
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
```
3.在Mapper接口中添加分页查询方法,使用MybatisPlus提供的Page对象进行分页查询:
```
public interface UserMapper extends BaseMapper<User> {
/**
* 分页查询用户列表
* @param page 分页参数
* @return 用户列表
*/
List<User> selectUserList(Page<User> page);
}
```
4.在Service层中调用Mapper接口中的分页查询方法,将查询结果封装到Page对象中返回给Controller层:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Page<User> getUserList(Page<User> page) {
return userMapper.selectUserList(page);
}
}
```
5.在Controller层中接收前端传来的分页参数,调用Service层中的分页查询方法,将查询结果返回给前端:
```
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public Result getUserList(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
Page<User> userList = userService.getUserList(page);
return Result.success(userList);
}
}
```
阅读全文
相关推荐

















