目录

1. mp官网

2. mp依赖

3. mp拦截器配置

4. sql注入器

5. 动态sql


1. mp官网

MyBatis-Plus 🚀 为简化开发而生

任何时候官网和源码都是我们最好的学习资料

2. mp依赖

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.5.7</version>
        </dependency>

3. mp拦截器配置

@Configuration
public class MybatisPlusConf {
    private static final Logger log = LoggerFactory.getLogger(MybatisPlusConf.class);

    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        paginationInterceptor.setMaxLimit(-1L);
        log.info("注册mp分页插件");
        return paginationInterceptor;
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.setInterceptors(Collections.singletonList(paginationInnerInterceptor()));
        log.info("注册mp拦截器");
        return mybatisPlusInterceptor;
    }


    // MySqlInjector 
}

下面这段代码在extension源码中,可以看到还可以添加很多的 InnerInterceptor

添加自定义功能只需要实现InnerInterceptor这个接口,将其添加到MybatisPlusInterceptor拦截器中

4. sql注入器

在源码中我们发现了List<AbstractMethod> methodList = super.getMethodList(configuration, mapperClass, tableInfo)这行代码

我们跳转到这个父类里面,我们可以看到注入了很多的方法

我们进入其中一个,可以看到这是一个构建sql的方法

继续查看SqlMethod,看以看到是枚举类定义了这些支持的方法

综上,所以我们也可以通过继承DefaultSqlInjector类重写getMethodList方法,注入我们自定义构建sql的方法

public class MySqlInjector extends DefaultSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
       
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);

        methodList.add(new AbstractMethod("methodName") {
            @Override
            public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
                // 自定义
                return null;
            }
        });
        return methodList;
    }
}

5. 动态sql

动态 SQL_MyBatis中文网

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐