MybatisPlus-分頁插件


1、配置分頁插件

創建配置包,到包下創建配置文件:MyBatisPlusConfig

@MapperScan("com.cn.springbootmybatisplus06.mapper")
@EnableTransactionManagement//自動管理事務
@Configuration // 配置類
public class MyBatisPlusConfig {

    /**
     * 新版
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //配置樂觀鎖
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        //配置分頁插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}

 

測試:

@SpringBootTest
public class TestMyFY {
    //測試分頁
    @Autowired
    private UserMapper userMapper;

    @Test
    public void MyFY(){
        //前端傳入數據
        Integer ye=2;
        //第二頁,每頁3行
        Page<User> page=new Page<>(ye,3);
        userMapper.selectPage(page,null);
        System.out.println(page);
    }
}

 

 

 

如果 MybatisPlus 不滿足我們的分頁需求,可以自定義分頁:

1、創建接口方法

  /**
     * 自定義分頁方法
     * @param page MybatisPlus 給我們提高的分頁功能,必須放在第一個
     * @param age  以年齡為條件進行分頁
     * @return
     */
    Page<User>  selectPageMyAge(@Param("page") Page<User> page, @Param("age") Integer age);

 

2、到 application.properties 中開啟別名配置

#配置類型別名
mybatis-plus.type-aliases-package=com/cn/springbootmybatisplus06/pojo

 

3、配置接口的實現 xml 配置文件

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

提示:這里有個坑,就是在查詢語句最后也就是  #{age} 后面不能加 ;號,因為它還要加分頁語句,使用不能結束。

 

4、分頁測試

  @Test
    public void MyFY2(){
        //前端傳入數據,頁數和年齡
        Integer ye=1;
        Integer age=20;
        //第1頁,每頁3行
        Page<User> page=new Page<>(ye,3);
        userMapper.selectPageMyAge(page,15);
        System.out.println(page);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM