在Spring Boot中使用MyBatis实现分页查询,可以通过插件PageHelper来简化操作。以下是具体的实现步骤:
添加PageHelper依赖在pom.xml文件中添加PageHelper的依赖:
<groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>5.2.0</version></dependency>配置PageHelper在application.properties或application.yml文件中添加PageHelper的配置:
# application.propertiespagehelper.helper-dialect=mysqlpagehelper.reasonable=truepagehelper.support-methods-arguments=truepagehelper.params=count=countSql或者
# application.ymlpagehelper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql创建分页查询接口在Mapper接口中,添加一个分页查询的方法:
public interface UserMapper { List<User> findAllWithPagination(RowBounds rowBounds);}实现分页查询接口在对应的XML文件中,编写分页查询的SQL语句:
SELECT * FROM user</select>在Service中使用分页查询@Servicepublic class UserService { @Autowired private UserMapper userMapper; public PageInfo<User> findAllWithPagination(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<User> users = userMapper.findAllWithPagination(new RowBounds()); return new PageInfo<>(users); }}在Controller中调用Service@RestController@RequestMapping("/user")public class UserController { @Autowired private UserService userService; @GetMapping("/pagination") public ResponseEntity<PageInfo<User>> getUsersWithPagination(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) { PageInfo<User> pageInfo = userService.findAllWithPagination(pageNum, pageSize); return ResponseEntity.ok(pageInfo); }}现在你可以通过访问/user/pagination?pageNum=1&pageSize=10来进行分页查询。其中pageNum表示页码,pageSize表示每页显示的记录数。


