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

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

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

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

2-1:引入依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>

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

public interface EntityDemoMapper extends BaseMapper<EntityDemo> {
    
    
    default List<EntityDemo> selectPage(int pageNum, int pageSize) {
    
    
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 执行查询
        //分页
        List<EntityDemo> entityDemoOne = entityDemoMapper.testSql(); 
        //未分页
        List<EntityDemo> entityDemoTwo = entityDemoMapper.testSql();
        return entityDemoOne ;
    }
}

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

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

<!-- MyBatis-Plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

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

@Configuration
public class MyBatisPlusConfig {
    
    
    @Bean
    //这是mybatis-plus3.4和3.5版本
    public MybatisPlusInterceptor paginationInterceptor() {
    
    
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}
@Configuration
public class MyBatisPlusConfig {
    
    
    @Bean
    //这是mybatis-plus3.5以下版本
    public PaginationInterceptor paginationInterceptor() {
    
    
        return new PaginationInterceptor();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_19891197/article/details/132691962