MyBatis在Spring Boot中的分頁查詢?nèi)绾螌?shí)現(xiàn)

小樊
85
2024-09-11 20:07:22
欄目: 編程語言

在Spring Boot中使用MyBatis實(shí)現(xiàn)分頁查詢,可以通過插件PageHelper來簡(jiǎn)化操作。以下是具體的實(shí)現(xiàn)步驟:

  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. 創(chuàng)建分頁查詢接口

在Mapper接口中,添加一個(gè)分頁查詢的方法:

public interface UserMapper {
    List<User> findAllWithPagination(RowBounds rowBounds);
}
  1. 實(shí)現(xiàn)分頁查詢接口

在對(duì)應(yīng)的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中調(diào)用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);
    }
}

現(xiàn)在你可以通過訪問/user/pagination?pageNum=1&pageSize=10來進(jìn)行分頁查詢。其中pageNum表示頁碼,pageSize表示每頁顯示的記錄數(shù)。

0