springboot几种sql分页查询(分页实现)

我会带着你远行 2024-03-08 08:00 168阅读 0赞

1:使用 LIMIT #{offset}, #{limit} 进行分页,使用 @Param 注解来传递分页参数,并在 SQL 语句中使用分页关键字

  1. public interface EntityDemoMapper extends BaseMapper<EntityDemo> {
  2. @Select("SELECT * FROM entity_demo LIMIT #{offset}, #{limit}")
  3. List<EntityDemo> selectPage(@Param("offset") int offset, @Param("limit") int limit);
  4. }

2:使用 PageHelper 这个工具类来实现

2-1:引入依赖

  1. <dependency>
  2. <groupId>com.github.pagehelper</groupId>
  3. <artifactId>pagehelper-spring-boot-starter</artifactId>
  4. <version>1.3.0</version>
  5. </dependency>

2-2:使用 PageHelper.startPage(pageNum, pageSize) 来开启分页功能。这个方法会将后续执行的第一个查询进行分页处理,第二个查询就不会分页,需要分页还需要在查询上面加一行entityDemoOne

  1. public interface EntityDemoMapper extends BaseMapper<EntityDemo> {
  2. default List<EntityDemo> selectPage(int pageNum, int pageSize) {
  3. // 开启分页
  4. PageHelper.startPage(pageNum, pageSize);
  5. // 执行查询
  6. //分页
  7. List<EntityDemo> entityDemoOne = entityDemoMapper.testSql();
  8. //未分页
  9. List<EntityDemo> entityDemoTwo = entityDemoMapper.testSql();
  10. return entityDemoOne ;
  11. }
  12. }

3: Spring Boot 中,要使 MyBatis-Plus 的分页插件生效,你需要进行以下配置步骤

3-1:导入依赖mybatis-plus,对应版本3.4版本兼容新旧插件,3.5.1开始不兼容旧插件类(PaginationInterceptor)

  1. <!-- MyBatis-Plus -->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>最新版本</version>
  6. </dependency>

3-2:注册分页插件:创建一个配置类,用于注册 MyBatis-Plus 的分页插件

  1. @Configuration
  2. public class MyBatisPlusConfig {
  3. @Bean
  4. //这是mybatis-plus3.4和3.5版本
  5. public MybatisPlusInterceptor paginationInterceptor() {
  6. MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
  7. mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  8. return mybatisPlusInterceptor;
  9. }
  10. }
  11. @Configuration
  12. public class MyBatisPlusConfig {
  13. @Bean
  14. //这是mybatis-plus3.5以下版本
  15. public PaginationInterceptor paginationInterceptor() {
  16. return new PaginationInterceptor();
  17. }
  18. }

发表评论

表情:
评论列表 (有 0 条评论,168人围观)

还没有评论,来说两句吧...

相关阅读

    相关 sql查询

    文章目录 分页查询 oracle中分页查询 mysql中分页查询 分页查询 > 分页查询在绝大多数项目中都会用到。如