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

官网上写着

       

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

3.0.3版本的写法

               

也就是中间加了一层,原来是AutoSqlInjector,现在改为AbstractSqlInjector.

源码如图:

            

写出自己的方法,命名为MyInjector,继承AbstractInjector.有个必须继承实现的方法getMethodList();如上图,继承后如下

           

然后,就是模仿写法,这里我是模仿的LogicSqlInjector,源码如图,也是继承AbstractSqlInjector,实现了getMethodList();

          

 

           

 上图就是Logic 的写法,我们要关注大块,就是返回一个Stream.of(new DeleteAll()).collect(Collectors.toList()),Stream.of()中间加了一个对象,然后打开这个对象,就可以看到对象的写法.

      

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

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

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

       

 

创建DeleteAll类,继承AbstractMethod,实现其方法,将Logic的injectMappedStatement中的内容复制下来,改写成自己的,在Logic中的SqlMethod是个枚举类型,所以建立一个MySqlMethod,查看Sqlmethod,对其源码进行复制改写.

DeleteAll代码.

 1 /**
 2  * 删除
 3  * @author liuyangos8888
 4  */
 5 public class DeleteAll extends AbstractMethod {
 6 
 7     @Override
 8     public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
 9         String sql;
10         MySqlMethod mySqlMethod = MySqlMethod.DELETE_ALL;
11         if (tableInfo.isLogicDelete()) {
12             sql = String.format(mySqlMethod.getSql(), tableInfo.getTableName(),  tableInfo,
13                     sqlWhereEntityWrapper(tableInfo));
14         } else {
15             mySqlMethod = MySqlMethod.DELETE_ALL;
16             sql = String.format(mySqlMethod.getSql(), tableInfo.getTableName(),
17                     sqlWhereEntityWrapper(tableInfo));
18         }
19         SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
20         return addUpdateMappedStatement(mapperClass, modelClass, mySqlMethod.getMethod(), sqlSource);
21     }
22 }
View Code

 

LogicDelete源码
 1 /**
 2  * <p>
 3  * 根据 queryWrapper 删除
 4  * </p>
 5  *
 6  * @author hubin
 7  * @since 2018-06-13
 8  */
 9 public class LogicDelete extends AbstractLogicMethod {
10 
11     @Override
12     public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
13         String sql;
14         SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE;
15         if (tableInfo.isLogicDelete()) {
16             sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo),
17                 sqlWhereEntityWrapper(tableInfo));
18         } else {
19             sqlMethod = SqlMethod.DELETE;
20             sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
21                 sqlWhereEntityWrapper(tableInfo));
22         }
23         SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
24         return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
25     }
26 }
View Code

MySqlMethod代码

 1 package com.baidu.www.injector;
 2 
 3 
 4 /**
 5  * 自定义全局删除方法
 6  */
 7 
 8 public enum MySqlMethod {
 9 
10 
11     /**
12      * 删除全部
13      */
14     DELETE_ALL("deleteAll", "根据 entity 条件删除记录", "<script>\nDELETE FROM %s %s\n</script>");
15 
16 
17     private final String method;
18     private final String desc;
19     private final String sql;
20 
21     MySqlMethod(String method, String desc, String sql) {
22         this.method = method;
23         this.desc = desc;
24         this.sql = sql;
25     }
26 
27     public String getMethod() {
28         return method;
29     }
30 
31     public String getDesc() {
32         return desc;
33     }
34 
35     public String getSql() {
36         return sql;
37     }
38 
39 }
View Code
SqlMethod源码
 1 package com.baidu.www.injector;
 2 
 3 
 4 /**
 5  * 自定义全局删除方法
 6  */
 7 
 8 public enum MySqlMethod {
 9 
10 
11     /**
12      * 删除全部
13      */
14     DELETE_ALL("deleteAll", "根据 entity 条件删除记录", "<script>\nDELETE FROM %s %s\n</script>");
15 
16 
17     private final String method;
18     private final String desc;
19     private final String sql;
20 
21     MySqlMethod(String method, String desc, String sql) {
22         this.method = method;
23         this.desc = desc;
24         this.sql = sql;
25     }
26 
27     public String getMethod() {
28         return method;
29     }
30 
31     public String getDesc() {
32         return desc;
33     }
34 
35     public String getSql() {
36         return sql;
37     }
38 
39 }
View Code
MyInjector代码
 1 package com.baidu.www.injector;
 2 
 3 import com.baomidou.mybatisplus.core.injector.AbstractMethod;
 4 import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;
 5 
 6 import java.util.List;
 7 import java.util.stream.Collectors;
 8 import java.util.stream.Stream;
 9 
10 /**
11  * 自定义全局操作
12  *
13  * @author liuyangos8888
14  */
15 public class MyInjector extends AbstractSqlInjector {
16 
17 
18     @Override
19     public List<AbstractMethod> getMethodList() {
20         return Stream.of(
21                 new DeleteAll()
22         ).collect(Collectors.toList());
23     }
24 
25 }
View Code
LogicSqlInjector源码
 1 /**
 2  * <p>
 3  * SQL 逻辑删除注入器
 4  * </p>
 5  *
 6  * @author hubin
 7  * @since 2018-06-12
 8  */
 9 public class LogicSqlInjector extends AbstractSqlInjector {
10 
11 
12     @Override
13     public List<AbstractMethod> getMethodList() {
14         return Stream.of(
15             new Insert(),
16             new LogicDelete(),
17             new LogicDeleteByMap(),
18             new LogicDeleteById(),
19             new LogicDeleteBatchByIds(),
20             new LogicUpdate(),
21             new LogicUpdateById(),
22             new LogicSelectById(),
23             new LogicSelectBatchByIds(),
24             new LogicSelectByMap(),
25             new LogicSelectOne(),
26             new LogicSelectCount(),
27             new LogicSelectMaps(),
28             new LogicSelectMapsPage(),
29             new LogicSelectObjs(),
30             new LogicSelectList(),
31             new LogicSelectPage()
32         ).collect(Collectors.toList());
33     }
View Code

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

 1 <!--定义mybatisplus全局配置-->
 2     <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
 3 
 4         <property name="dbConfig">
 5             <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
 6                 <!-- 全局的主键策略 -->
 7                 <property name="idType" value="AUTO"/>
 8                 <!-- 全局的表前缀策略配置 -->
 9                 <property name="tablePrefix" value="tbl_"/>
10 
11                 <!--逻辑删除全局配值-->
12                 <property name="logicDeleteValue" value="0"/>
13                 <property name="logicNotDeleteValue" value="1"/>
14 
15             </bean>
16         </property>
17 
18         <!--&lt;!&ndash;注入自定义全局操作&ndash;&gt;-->
19         <property name="sqlInjector" ref="mySqlInjector"/>
20 
21         <!--<property name="sqlInjector" ref="logicSqlInjector"/>-->
22 
23 
24     </bean>
25 
26 
27     <!--自定义注入器-->
28 
29     <bean id="mySqlInjector" class="com.baidu.www.injector.MyInjector"/>
View Code

全部

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans"
  3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4        xmlns:context="http://www.springframework.org/schema/context"
  5        xmlns:tx="http://www.springframework.org/schema/tx"
  6        xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
  7        xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring
  8     http://mybatis.org/schema/mybatis-spring-1.2.xsd
  9     http://www.springframework.org/schema/beans
 10     http://www.springframework.org/schema/beans/spring-beans.xsd
 11     http://www.springframework.org/schema/context
 12     http://www.springframework.org/schema/context/spring-context-4.0.xsd
 13     http://www.springframework.org/schema/tx
 14     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
 15     <!-- 数据源 -->
 16     <context:property-placeholder location="classpath:db.properties"/>
 17 
 18     <bean id="dataSource"
 19           class="com.mchange.v2.c3p0.ComboPooledDataSource">
 20         <property name="driverClass" value="${jdbc.driver}"/>
 21         <property name="jdbcUrl" value="${jdbc.url}"/>
 22         <property name="user" value="${jdbc.username}"/>
 23         <property name="password" value="${jdbc.password}"/>
 24     </bean>
 25 
 26     <!-- 事务管理器 -->
 27     <bean id="dataSourceTransactionManager"
 28           class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 29         <property name="dataSource" ref="dataSource"/>
 30     </bean>
 31 
 32     <!-- 基于注解的事务管理 -->
 33     <tx:annotation-driven
 34             transaction-manager="dataSourceTransactionManager"/>
 35 
 36     <!--&lt;!&ndash;修改为MybatisPlus配置&ndash;&gt;-->
 37     <bean id="sqlSessionFactoryBean" class=" com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean ">
 38 
 39         <!-- 数据源 -->
 40         <property name="dataSource" ref="dataSource"/>
 41 
 42         <property name="configLocation" value="classpath:mybatis-config.xml"/>
 43 
 44         <!-- 别名处理 -->
 45         <property name="typeAliasesPackage" value="com.baidu.www.bean"/>
 46 
 47         <!--注入全局MP策略配置-->
 48         <property name="globalConfig" ref="globalConfig"/>
 49 
 50         <!--插件配置-->
 51 
 52         <property name="plugins">
 53             <list>
 54 
 55                 <!--注册分页插件-->
 56                 <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/>
 57 
 58                 <!--注册执行分析插件,生产环境不建议使用-->
 59                 <!--<bean class="com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor"/>-->
 60                 <!--&lt;!&ndash;<property name="properties" ref="">&ndash;&gt;-->
 61 
 62                 <!--&lt;!&ndash;</property>&ndash;&gt;-->
 63                 <!--</bean>-->
 64 
 65                 <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->
 66                 <bean class="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor">
 67                     <property name="maxTime" value="100"/>
 68                     <!--SQL是否格式化 默认false-->
 69                     <property name="format" value="true"/>
 70                 </bean>
 71 
 72                 <!--乐观锁插件-->
 73                 <bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>
 74 
 75             </list>
 76         </property>
 77 
 78     </bean>
 79 
 80     <!--定义mybatisplus全局配置-->
 81     <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
 82 
 83         <property name="dbConfig">
 84             <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
 85                 <!-- 全局的主键策略 -->
 86                 <property name="idType" value="AUTO"/>
 87                 <!-- 全局的表前缀策略配置 -->
 88                 <property name="tablePrefix" value="tbl_"/>
 89 
 90                 <!--逻辑删除全局配值-->
 91                 <property name="logicDeleteValue" value="0"/>
 92                 <property name="logicNotDeleteValue" value="1"/>
 93 
 94             </bean>
 95         </property>
 96 
 97         <!--&lt;!&ndash;注入自定义全局操作&ndash;&gt;-->
 98         <property name="sqlInjector" ref="mySqlInjector"/>
 99 
100         <!--<property name="sqlInjector" ref="logicSqlInjector"/>-->
101 
102 
103     </bean>
104 
105 
106     <!--自定义注入器-->
107 
108     <bean id="mySqlInjector" class="com.baidu.www.injector.MyInjector"/>
109 
110 
111     <!--逻辑删除-->
112     <!--<bean id="logicSqlInjector" class="com.baomidou.mybatisplus.extension.injector.LogicSqlInjector"/>-->
113 
114 
115     <!--配置 mybatis 扫描 mapper 接口的路径 -->
116     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
117         <property name="basePackage"
118                   value="com.baidu.www.mapper">
119 
120         </property>
121     </bean>
122 </beans>
View Code

添加到mapper.

 1 package com.baidu.www.mapper;
 2 
 3 import com.baidu.www.bean.Employee;
 4 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 5 
 6 /**
 7  * <p>
 8  *  Mapper 接口
 9  * </p>
10  *
11  * @author Mr.Liu
12  * @since 2018-10-04
13  */
14 public interface EmployeeMapper extends BaseMapper<Employee> {
15 
16 
17     Integer deleteAll();
18 
19 
20 }
View Code

测试

 1 public class TestGenerator {
 2 
 3 
 4     private ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationContext.xml");
 5 
 6     EmployeeMapper employeeMapper = iocContext.getBean("employeeMapper", EmployeeMapper.class);
 7 
 8     private Logger logger = LoggerFactory.getLogger(TestGenerator.class);
 9 
10     Gson gson = new Gson();
11 
12     /**
13      * 测试分页插件
14      *
15      * @throws SQLException
16      */
17     @Test
18     public void testInterceptor() throws SQLException {
19 
20 
21         Integer result = employeeMapper.deleteAll();
22 
23 
24         if (result > 0) {
25 
26             logger.info("删除成功:" + result);
27 
28         }
29 
30     }
31 }
View Code

 

找了很多资料都没有3.0.3的答案,我就自己看源码,看到懂了,就改了这个,希望对你有帮助,源码如下:

https://github.com/liushaoye/mplus005

 

 

 

posted @ 2018-10-05 01:15  北极的大企鹅  阅读(19251)  评论(10编辑  收藏