Spring Boot

MyBatis在Spring Boot中的分页查询如何实现

小樊
83
2024-09-11 20:07:22
栏目: 编程语言

在Spring Boot中使用MyBatis实现分页查询,可以通过插件PageHelper来简化操作。以下是具体的实现步骤:

  1. 添加PageHelper依赖

pom.xml文件中添加PageHelper的依赖:

   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper-spring-boot-starter</artifactId>
   <version>5.2.0</version>
</dependency>
  1. 配置PageHelper

application.propertiesapplication.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
  1. 创建分页查询接口

在Mapper接口中,添加一个分页查询的方法:

public interface UserMapper {
    List<User> findAllWithPagination(RowBounds rowBounds);
}
  1. 实现分页查询接口

在对应的XML文件中,编写分页查询的SQL语句:

    SELECT * FROM user
</select>
  1. 在Service中使用分页查询
@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);
    }
}
  1. 在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表示每页显示的记录数。

0
看了该问题的人还看了