亲宝软件园·资讯

展开

详解MyBatis Plus中分页插件的使用

世界尽头与你 人气:0

MyBatis Plus分页插件使用

MyBatis Plus中使用分页插件也很简单:

首先编写配置类:

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 构造拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

大功告成!现在来测试一下吧:

@Test
void contextLoads() {
    Page<User> page = new Page<>(1, 2);
    userMapper.selectPage(page, null);
    System.out.println(page);
}

==>  Preparing: SELECT COUNT(*) AS total FROM user WHERE is_delete = 0
==> Parameters: 
<==    Columns: total
<==        Row: 3
<==      Total: 1
==>  Preparing: SELECT id,name,age,email,is_delete FROM user WHERE is_delete=0 LIMIT ?
==> Parameters: 2(Long)
<==    Columns: id, name, age, email, is_delete
<==        Row: 2, hello, 33, 111@qq.com, 0
<==        Row: 3, hello, 18, 34567@qq.com, 0
<==      Total: 2

也可以很容易的获取分页相关的数据:

程序实例:

@Test
void contextLoads() {
    Page<User> page = new Page<>(1, 2);
    userMapper.selectPage(page, null);
    // 获取当前页的记录
    List<User> records = page.getRecords();
    records.forEach(System.out::println);
    // 获取当前页的页码
    long current = page.getCurrent();
    System.out.println(current);
    // 获取分页的总页码数
    long size = page.getSize();
    System.out.println(size);
    // 判断是否有下一页
    boolean b = page.hasNext();
    System.out.println(b);
    // 判断是否有上一页
    boolean b1 = page.hasPrevious();
    System.out.println(b1);
}

自定义分页功能

首先,定义一个mapper接口,返回一个Page对象:

Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);

实现mapper接口:

<select id="selectPageVo" resultType="User">
    select id,name,age,email from user where age = #{age}
</select>

我们使用了类型别名,不要忘记在配置类中开启扫描类型别名所在的包:

mybatis-plus:
  ...
  # 配置类型别名对应的包
  type-aliases-package: com.klza.pojo

现在来测试一下吧:

@Test
void contextLoads() {
    Page<User> page = new Page<>(1, 2);
    Page<User> userPage = userMapper.selectPageVo(page, 18);
    System.out.println(userPage);
}

==>  Preparing: SELECT COUNT(*) AS total FROM user WHERE age = ?
==> Parameters: 18(Integer)
<==    Columns: total
<==        Row: 2
<==      Total: 1
==>  Preparing: select id,name,age,email from user where age = ? LIMIT ?
==> Parameters: 18(Integer), 2(Long)
<==    Columns: id, name, age, email
<==        Row: 3, hello, 18, 34567@qq.com
<==        Row: 4, hello, 18, 34567@qq.com
<==      Total: 2

加载全部内容

相关教程
猜你喜欢
用户评论