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