在Spring Boot中使用MyBatis实现分页查询,可以通过插件PageHelper来简化操作。以下是具体的实现步骤:
在pom.xml
文件中添加PageHelper的依赖:
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>5.2.0</version>
</dependency>
在application.properties
或application.yml
文件中添加PageHelper的配置:
# application.properties
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
或者
# application.yml
pagehelper:
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
public 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);
}
}
@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
表示每页显示的记录数。