【Mybatis分页拦截器使用】

使用mybatis后,很多增删改查,编写一些crud之类的mapper.xml mapperDao.java的代码基本都形成套路的模式。 这时使用mybatis-plus就是简化这一工作量的好方法。

mybatis-plus处理的分页的方法

1. 注入配置文件

老版本是注入一个PaginationInterceptor拦截器, 而新版本是使用生成一个MybatisPlusInterceptor拦截器对象然后,将你使用的数据库对应方言添加进拦截器对象。

package com.hxstrive.mybatis_plus;
 
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MybatisPlusConfig {
 
    /**
     * 分页插件。如果你不配置,分页插件将不生效
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 指定数据库方言为 MYSQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

springboot启动程序中加入扫描mapper文件夹的注解

@SpringBootApplication
@MapperScan("com.bgp.project.mapper")
public class ProjectServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProjectServiceApplication.class, args);
    }

}

3. 编写mapper类

在这里mybatis展现出它的强大,mapper类只要继承BaseMapper,并实现接口的泛型。就可以对泛型对象对应的数据库进行最基本的crud和很多强大的功能而不需要任何其它代码和编写xml映射文件

@Repository
public interface ProjectMapper extends BaseMapper<Project> {
	//继承BaseMapper<T>就行了,其余的什么都不用做
}

4. 分页查询

mybatis-plus大大简化了分页查询

//封装一个实体类的查询对象
QueryWrapper<Project> condition = new QueryWrapper<>();
condition.isNotNull("id");//设置一个查询条件,如果不设置返回all

//1.返回一个Map类型
Page<Map<String,Object>> page = new Page<>(1, 4);
projectMapper.selectMapsPage(page, condition);
projectMapper.selectMapsPage(page, null);

//2. 返回一个Page封装的实体类列表
Page<Project> page = new Page<>(1, 4);
Page<Project> result = projectMapper.selectPage(page, wrapper);
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dangkei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值