在Spring Boot中使用MyBatis實(shí)現(xiàn)分頁查詢,可以通過插件PageHelper來簡(jiǎn)化操作。以下是具體的實(shí)現(xiàn)步驟:
在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接口中,添加一個(gè)分頁查詢的方法:
public interface UserMapper {
List<User> findAllWithPagination(RowBounds rowBounds);
}
在對(duì)應(yīng)的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);
}
}
現(xiàn)在你可以通過訪問/user/pagination?pageNum=1&pageSize=10
來進(jìn)行分頁查詢。其中pageNum
表示頁碼,pageSize
表示每頁顯示的記錄數(shù)。