目录:

  一、Mybatis 分页

       一、LIMIT关键字

       二、RowBounds实现分页

       三、PageHelper

  二、Mybatis-plus分页

一、Mybatis 实现分页

(1)使用 LIMIT 关键字

业务层将pageNo 和pageSize传过来,即可实现分页操作。

灵活性高,可优化空间大,但是对于新手比较复杂。

<select id="selectByPageo" resultMap="Result">
    select * from user limit #{pageNo}, #{pageSize}
</select>

(2)RowBounds实现分页

Mybatis官方提供RowBounds类来实现逻辑分页。RowBounds中有2个字段offset和limit。这种方式获取所有的ResultSet,从ResultSet中的offset位置开始获取limit个记录。

 只需要填充两个参数到RowBounds中,即可使用。

controller层:

   RowBounds rowBounds = new RowBounds(page, size);

mapper层:

 List<ExamManage> findpage(RowBounds rowBounds);

mapper.xml:

   <select id="findpage" resultType="ExamManage">
        select * from exam_manage
   </select>

三、PageHelper实现分页

PageHelper是一个第三方实现的分页拦截器插件。

 添加pom依赖:

		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.3.1</version>
		</dependency>

 直接使用pagehelper方法,更加简便。

  二、Mybatis-plus分页

(1)加入pom依赖

        <!-- MyBatisX插件 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

(2)在启动类同层写个Mybatis-plus配置类:

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.exam.service.*.mapper*")
public class MybatisPlusConfig {
    /**
     * 分页插件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

 (3)传入参数,构建Page<>对象 

最后,实现完整的查询操作即可。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐