MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

官网状况

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

但是,这个其实是2.0系列的写法,由于引用了最新的3.0.3这个功能基本不好使.

查看源码结构

继承关系

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

根据框架新旧的对比,得出3.0版的框架增加了一层继承,就是原来是AutoSqlInjector,现在改为AbstractSqlInjector.

源码结构

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

如何改写

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

创建一个自己的MyInjector,继承框架中的AbstractSQLInjector,有个必须继承实现的方法getMethodList();

模仿框架中已有的方法,进行自定义的改写

结构与源码

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

进入改写代码块位置

    其实上图代码的结构重点就是: Stream.of(new DeleteAll()).collect(Collectors.toList())
    Stream.of()中间加了一个对象,然后打开这个对象,就可以看到对象的写法.

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写
MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写

结构如上图,就是继承了AbstractLogicMethod,打开一看这个方法是其自己自定义的一个方法,我们根本用不到(暂时),所以我们继承其公有父类AbstractMethod

现在结构就是很清晰了,MyInjector继承了AbstractInjector类,实现了其getMethod方法,getMethod方法返回一个Stream.of( ).collect(Collectors.toList()),Dream.of()中封装一个对象,是实际的Sql注入方法的写法.

这个写法需要继承AbstractMethod实现其injectMappedStatement方法,所以也不用记什么,滤清逻辑改写就可以了.结构

实战改写演练

项目结构

MyBatis-Plus 3.0.3 Sql注入器添加,即全局配置Sql注入器,sqlInjector改写
创建DeleteAll类,继承AbstractMethod,实现其方法,将Logic的injectMappedStatement中的内容复制下来,改写成自己的,在Logic中的SqlMethod是个枚举类型,所以建立一个MySqlMethod,查看Sqlmethod,对其源码进行复制改写.

DeleteAll代码.

 /**
  * 删除
  * @author mrliu8888
 */
 public class DeleteAll extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql;
        MySqlMethod mySqlMethod = MySqlMethod.DELETE_ALL;
        if (tableInfo.isLogicDelete()) {
            sql = String.format(mySqlMethod.getSql(), tableInfo.getTableName(),  tableInfo,
                    sqlWhereEntityWrapper(tableInfo));
        } else {
            mySqlMethod = MySqlMethod.DELETE_ALL;
           sql = String.format(mySqlMethod.getSql(), tableInfo.getTableName(),
                   sqlWhereEntityWrapper(tableInfo));
       }
       SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
       return addUpdateMappedStatement(mapperClass, modelClass, mySqlMethod.getMethod(), sqlSource);
  }
}

LogicDelete源码

   /**
 * <p>
 * 根据 queryWrapper 删除
 * </p>
 *
 * @author hubin
 * @since 2018-06-13
 */
public class LogicDelete extends AbstractLogicMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql;
        SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE;
        if (tableInfo.isLogicDelete()) {
            sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo),
                sqlWhereEntityWrapper(tableInfo));
        } else {
            sqlMethod = SqlMethod.DELETE;
            sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
                sqlWhereEntityWrapper(tableInfo));
        }
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
    }
}

MySqlMethod代码

   package com.baidu.www.injector;


   /**
    * 自定义全局删除方法
    */

    public enum MySqlMethod {


    /**
     * 删除全部
     */
    DELETE_ALL("deleteAll", "根据 entity 条件删除记录", "<script>\nDELETE FROM %s %s\n</script>");


    private final String method;
    private final String desc;
    private final String sql;

    MySqlMethod(String method, String desc, String sql) {
        this.method = method;
        this.desc = desc;
        this.sql = sql;
    }

    public String getMethod() {
        return method;
    }

    public String getDesc() {
        return desc;
    }

    public String getSql() {
        return sql;
    }

}

SqlMethod源码

package com.baidu.www.injector;


/**
 * 自定义全局删除方法
 */

public enum MySqlMethod {


    /**
     * 删除全部
     */
    DELETE_ALL("deleteAll", "根据 entity 条件删除记录", "<script>\nDELETE FROM %s %s\n</script>");


    private final String method;
    private final String desc;
    private final String sql;

    MySqlMethod(String method, String desc, String sql) {
        this.method = method;
        this.desc = desc;
        this.sql = sql;
    }

    public String getMethod() {
        return method;
    }

    public String getDesc() {
        return desc;
    }

    public String getSql() {
        return sql;
    }

}

MyInjector代码


package com.baidu.www.injector;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 自定义全局操作
 *
 * @author mrliu8888
 */
public class MyInjector extends AbstractSqlInjector {


    @Override
    public List<AbstractMethod> getMethodList() {
        return Stream.of(
                new DeleteAll()
        ).collect(Collectors.toList());
    }

}

LogicSqlInjector源码

 /**
 * <p>
 * SQL 逻辑删除注入器
 * </p>
 *
 * @author hubin
 * @since 2018-06-12
 */
public class LogicSqlInjector extends AbstractSqlInjector {


    @Override
    public List<AbstractMethod> getMethodList() {
        return Stream.of(
            new Insert(),
            new LogicDelete(),
            new LogicDeleteByMap(),
            new LogicDeleteById(),
            new LogicDeleteBatchByIds(),
            new LogicUpdate(),
            new LogicUpdateById(),
            new LogicSelectById(),
            new LogicSelectBatchByIds(),
            new LogicSelectByMap(),
            new LogicSelectOne(),
            new LogicSelectCount(),
            new LogicSelectMaps(),
            new LogicSelectMapsPage(),
            new LogicSelectObjs(),
            new LogicSelectList(),
            new LogicSelectPage()
        ).collect(Collectors.toList());
    }

最后修改其配置文件,加入到框架中


   <!--定义mybatisplus全局配置-->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">

        <property name="dbConfig">
            <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
                <!-- 全局的主键策略 -->
                <property name="idType" value="AUTO"/>
                <!-- 全局的表前缀策略配置 -->
                <property name="tablePrefix" value="tbl_"/>

                <!--逻辑删除全局配值-->
                <property name="logicDeleteValue" value="0"/>
                <property name="logicNotDeleteValue" value="1"/>

            </bean>
        </property>

        <!--&lt;!&ndash;注入自定义全局操作&ndash;&gt;-->
        <property name="sqlInjector" ref="mySqlInjector"/>

        <!--<property name="sqlInjector" ref="logicSqlInjector"/>-->


    </bean>


    <!--自定义注入器-->

    <bean id="mySqlInjector" class="com.baidu.www.injector.MyInjector"/>

全部

   <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
       xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring
    http://mybatis.org/schema/mybatis-spring-1.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <!-- 数据源 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 事务管理器 -->
    <bean id="dataSourceTransactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 基于注解的事务管理 -->
    <tx:annotation-driven
            transaction-manager="dataSourceTransactionManager"/>

    <!--&lt;!&ndash;修改为MybatisPlus配置&ndash;&gt;-->
    <bean id="sqlSessionFactoryBean" class=" com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean ">

        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>

        <property name="configLocation" value="classpath:mybatis-config.xml"/>

        <!-- 别名处理 -->
        <property name="typeAliasesPackage" value="com.baidu.www.bean"/>

        <!--注入全局MP策略配置-->
        <property name="globalConfig" ref="globalConfig"/>

        <!--插件配置-->

        <property name="plugins">
            <list>

                <!--注册分页插件-->
                <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/>

                <!--注册执行分析插件,生产环境不建议使用-->
                <!--<bean class="com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor"/>-->
                <!--&lt;!&ndash;<property name="properties" ref="">&ndash;&gt;-->

                <!--&lt;!&ndash;</property>&ndash;&gt;-->
                <!--</bean>-->

                <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->
                <bean class="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor">
                    <property name="maxTime" value="100"/>
                    <!--SQL是否格式化 默认false-->
                    <property name="format" value="true"/>
                </bean>

                <!--乐观锁插件-->
                <bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

            </list>
        </property>

    </bean>

    <!--定义mybatisplus全局配置-->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">

        <property name="dbConfig">
            <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
                <!-- 全局的主键策略 -->
                <property name="idType" value="AUTO"/>
                <!-- 全局的表前缀策略配置 -->
                <property name="tablePrefix" value="tbl_"/>

                <!--逻辑删除全局配值-->
                <property name="logicDeleteValue" value="0"/>
                <property name="logicNotDeleteValue" value="1"/>

            </bean>
        </property>

        <!--&lt;!&ndash;注入自定义全局操作&ndash;&gt;-->
        <property name="sqlInjector" ref="mySqlInjector"/>

        <!--<property name="sqlInjector" ref="logicSqlInjector"/>-->


    </bean>


    <!--自定义注入器-->

    <bean id="mySqlInjector" class="com.baidu.www.injector.MyInjector"/>


    <!--逻辑删除-->
    <!--<bean id="logicSqlInjector" class="com.baomidou.mybatisplus.extension.injector.LogicSqlInjector"/>-->


    <!--配置 mybatis 扫描 mapper 接口的路径 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"
                  value="com.baidu.www.mapper">

        </property>
    </bean>
</beans>

添加到mapper

package com.baidu.www.mapper;

import com.baidu.www.bean.Employee;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author Mr.Liu
 * @since 2018-10-04
 */
public interface EmployeeMapper extends BaseMapper<Employee> {


    Integer deleteAll();


}

测试

   public class TestGenerator {


    private ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    EmployeeMapper employeeMapper = iocContext.getBean("employeeMapper", EmployeeMapper.class);

    private Logger logger = LoggerFactory.getLogger(TestGenerator.class);

    Gson gson = new Gson();

    /**
     * 测试分页插件
     *
     * @throws SQLException
     */
    @Test
    public void testInterceptor() throws SQLException {


        Integer result = employeeMapper.deleteAll();


        if (result > 0) {

            logger.info("删除成功:" + result);

        }

    }
}

找了很多资料都没有3.0.3的答案,于是就自己看源码,看到懂了,就改了这个,如果您有什么疑问请留言,期待与您共同交流更多有趣的mybaitisplus的问题,和其他相关java的问题,我是北极的大企鹅
希望对你有帮助,
源码如下:
[0]: https://github.com/liushaoye/mplus005
欢迎关注我的其他博客
[1]: https://www.cnblogs.com/liuyangfirst/