mybatis有哪些分页方式?

249 阅读1分钟

常见的三种。

  • limit关键字
  • RowBounds分页
  • 分页拦截器pageHelper

limit

1.mapper代码

<select id="selectByPageInfo" resultMap="BaseResult">
 select * from tb_user limit #{pageNo}, #{pageSize}
</select>

2.业务层直接调用

public List<User> findByPageInfo(PageInfo info) {
 return userMapper.selectByPageInfo(info);
 }

RowBounds实现分页

1.mapper代码

 <select id="selectPage" resultType="com.example.demo.mapper.one.User">
        select * from user
    </select>

2.dao代码

    List<User> selectPage(RowBounds rowBounds);

3.分页查询

       List<User> users = userMapper.selectPage(new RowBounds(5, 10));
       log.info("users:{}",users);

分页拦截器pageHelper

该插件内部实现了PageInterceptor拦截器,mybatis会加载这个拦截器到拦截器链中。当我们调用PageHelper.startPage方法时,就会在当前线程中设置一个ThreadLocal变量来保存分页的信息,当分页拦截器拦截了sql语句时,就会从threadlocal中取出分页信息,动态的为sql语句拼接limit关键字。最后再把ThreadLocal中的分页信息清除。