首頁 > 軟體

詳解MyBatis Plus中分頁外掛的使用

2023-02-10 06:02:12

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

到此這篇關於詳解MyBatis Plus中分頁外掛的使用的文章就介紹到這了,更多相關MyBatis Plus分頁外掛內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com