MyBatis拦截器

一、拦截对象和接口实现示例

        MyBatis拦截器的作用是在于Dao到DB中间进行额外的处理。大部分情况下通过mybatis的xml配置sql都可以达到想要的DB操作效果,然而存在一些类似或者相同的查询条件或者查询要求,这些可以通过拦截器的实现可以提升开发效率,比如:分页、插入和更新时间/人、数据权限、SQL监控日志等。

  • Mybatis支持四种对象拦截Executor、StatementHandler、PameterHandler和ResultSetHandler

  1. Executor:拦截执行器的方法。

  2. StatementHandler:拦截Sql语法构建的处理。

  3. ParameterHandler:拦截参数的处理。

  4. ResultHandler:拦截结果集的处理。

 1 public interface Executor {
 2     ResultHandler NO_RESULT_HANDLER = null;
 3     int update(MappedStatement var1, Object var2) throws SQLException;
 4     <E> List<E> query(MappedStatement var1, Object var2, RowBounds var3, ResultHandler var4, CacheKey var5, BoundSql var6) throws SQLException;
 5     <E> List<E> query(MappedStatement var1, Object var2, RowBounds var3, ResultHandler var4) throws SQLException;
 6     <E> Cursor<E> queryCursor(MappedStatement var1, Object var2, RowBounds var3) throws SQLException;
 7     List<BatchResult> flushStatements() throws SQLException;
 8     void commit(boolean var1) throws SQLException;
 9     void rollback(boolean var1) throws SQLException;
10     CacheKey createCacheKey(MappedStatement var1, Object var2, RowBounds var3, BoundSql var4);
11     boolean isCached(MappedStatement var1, CacheKey var2);
12     void clearLocalCache();
13     void deferLoad(MappedStatement var1, MetaObject var2, String var3, CacheKey var4, Class<?> var5);
14     Transaction getTransaction();
15     void close(boolean var1);
16     boolean isClosed();
17     void setExecutorWrapper(Executor var1);
18 }
19 public interface StatementHandler {
20     Statement prepare(Connection var1, Integer var2) throws SQLException;
21     void parameterize(Statement var1) throws SQLException;
22     void batch(Statement var1) throws SQLException;
23     int update(Statement var1) throws SQLException;
24     <E> List<E> query(Statement var1, ResultHandler var2) throws SQLException;
25     <E> Cursor<E> queryCursor(Statement var1) throws SQLException;
26     BoundSql getBoundSql();
27     ParameterHandler getParameterHandler();
28 }
29 public interface ParameterHandler {
30     Object getParameterObject();
31     void setParameters(PreparedStatement var1) throws SQLException;
32 }
33 public interface ResultHandler<T> {
34     void handleResult(ResultContext<? extends T> var1);
35 }

     拦截的执行顺序是Executor->StatementHandler->ParameterHandler->ResultHandler

  • MyBatis提供的拦截器接口:

1 public interface Interceptor {
2     Object intercept(Invocation var1) throws Throwable;
3     default Object plugin(Object target) {
4         return Plugin.wrap(target, this);
5     }
6     default void setProperties(Properties properties) {}
7 }

  Object intercept方法用于拦截器的实现;

  Object plugin方法用于判断执行拦截器的类型;

  void setProperties方法用于获取配置项的属性。

  • 拦截对象和拦截器接口的结合,自定义的拦截器类需要实现拦截器接口,并通过注解@Intercepts和参数@Signature来声明要拦截的对象。

        @Signature参数type是拦截对象,method是拦截的方法,即上面的四个类对应的方法,args是拦截方法对应的参数(方法存在重载因此需要指明参数个数和类型)

         @Intercepts可以有多个@Signature,即一个拦截器实现类可以同时拦截多个对象及方法,示例如下:

    1. Executor->intercept

    2. StatementHandler->intercept

    3. ParameterHandler->intercept

    4. ResultHandler->intercept

 1 @Intercepts({
 2         @Signature(
 3                 type = Executor.class,
 4                 method = "query",
 5                 args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
 6         )
 7 })
 8 public class SelectPlugin implements Interceptor {
 9     @Override
10     public Object intercept(Invocation invocation) throws Throwable {
11         if (invocation.getTarget() instanceof Executor) {
12             System.out.println("SelectPlugin");
13         }
14         return invocation.proceed();
15     }
16     @Override
17     public Object plugin(Object target) {
18         if (target instanceof Executor) {
19             return Plugin.wrap(target, this);
20         }
21         return target;
22     }
23     @Override
24     public void setProperties(Properties properties) {}
25 }
26 @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
27 public class StatementPlugin implements Interceptor {
28     @Override
29     public Object intercept(Invocation invocation) throws Throwable {
30         if (invocation.getTarget() instanceof StatementHandler) {
31             System.out.println("StatementPlugin");
32         }
33         return invocation.proceed();
34     }
35     @Override
36     public Object plugin(Object target) {
37         if (target instanceof StatementHandler) {
38             return Plugin.wrap(target, this);
39         }
40         return target;
41     }
42     @Override
43     public void setProperties(Properties properties) {}
44 }
45 @Intercepts({@Signature(type = ParameterHandler.class,method = "setParameters",args = {PreparedStatement.class})})
46 public class ParameterPlugin implements Interceptor {
47     @Override
48     public Object intercept(Invocation invocation) throws Throwable {
49         if (invocation.getTarget() instanceof ParameterHandler) {
50             System.out.println("ParameterPlugin");
51         }
52         return invocation.proceed();
53     }
54     @Override
55     public Object plugin(Object target) {
56         if (target instanceof ParameterHandler) {
57             return Plugin.wrap(target, this);
58         }
59         return target;
60     }
61     @Override
62     public void setProperties(Properties properties) {}
63 }
64 @Intercepts({@Signature(type = ResultHandler.class,method = "handleResult",args = {ResultContext.class})})
65 public class ResultPlugin implements Interceptor {
66     @Override
67     public Object intercept(Invocation invocation) throws Throwable {
68         if (invocation.getTarget() instanceof ResultHandler) {
69             System.out.println("ResultPlugin");
70         }
71         return invocation.proceed();
72     }
73     @Override
74     public Object plugin(Object target) {
75         if (target instanceof ResultHandler) {
76             return Plugin.wrap(target, this);
77         }
78         return target;
79     }
80     @Override
81     public void setProperties(Properties properties) {}
82 }

二、拦截器注册的三种方式

        前面介绍了Mybatis的拦截对象及其接口的实现方式,那么在项目中如何注册拦截器呢?本文中给出三种注册方式。

        1.XML注册

        xml注册是最基本的方式,是通过在Mybatis配置文件中plugins元素来进行注册的。一个plugin对应着一个拦截器,在plugin元素可以指定property子元素,在注册定义拦截器时把对应拦截器的所有property通过Interceptor的setProperties方法注入给拦截器。因此拦截器注册xml方式如下:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <!-- ...... -->
 7     <plugins>
 8        <plugin interceptor="com.tiantian.mybatis.interceptor.MyInterceptor">
 9            <property name="prop1" value="prop1"/>
10            <property name="prop2" value="prop2"/>
11        </plugin>
12     </plugins>
13     <!-- ...... -->
14 </configuration>

        2.配置类注册

       配置类注册是指通过Mybatis的配置类中声明注册拦截器,配置类注册也可以通过Properties类给Interceptor的setProperties方法注入参数。具体参考如下:

 1 @Configuration
 2 public class MyBatisConfig {
 3     @Bean
 4     public String MyBatisInterceptor(SqlSessionFactory sqlSessionFactory) {
 5         UpdatePlugin executorInterceptor = new UpdatePlugin();
 6         Properties properties = new Properties();
 7         properties.setProperty("prop1", "value1");
 8         // 给拦截器添加自定义参数
 9         executorInterceptor.setProperties(properties);
10         sqlSessionFactory.getConfiguration().addInterceptor(executorInterceptor);
11         sqlSessionFactory.getConfiguration().addInterceptor(new StatementPlugin());
12         sqlSessionFactory.getConfiguration().addInterceptor(new ResultPlugin());
13         sqlSessionFactory.getConfiguration().addInterceptor(new ParameterPlugin());
14         // sqlSessionFactory.getConfiguration().addInterceptor(new SelectPlugin());
15         return "interceptor";
16     }
17 
18     // 与sqlSessionFactory.getConfiguration().addInterceptor(new SelectPlugin());效果一致
19     @Bean
20     public SelectPlugin SelectInterceptor() {
21         SelectPlugin interceptor = new SelectPlugin();
22         Properties properties = new Properties();
23         // 调用properties.setProperty方法给拦截器设置自定义参数
24         interceptor.setProperties(properties);
25         return interceptor;
26     }
27 }

        3.注解方式

          通过@Component注解方式是最简单的方式,在不需要转递自定义参数时可以使用,方便快捷。

@Component
@Intercepts({
        @Signature(
                type = Executor.class,
                method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        )
})
public class SelectPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (invocation.getTarget() instanceof Executor) {
            System.out.println("SelectPlugin");
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

三、ParameterHandler参数改写-修改时间和修改人统一插入

        针对具体的拦截器实现进行描述。日常编码需求中会碰到修改时需要插入修改的时间和人员,如果要用xml的方式去写非常麻烦,而通过拦截器的方式可以快速实现全局的插入修改时间和人员。先看代码:

 1 @Component
 2 @Intercepts({
 3         @Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class}),
 4 })
 5 public class MyBatisInterceptor implements Interceptor {
 6     @Override
 7     public Object intercept(Invocation invocation) throws Throwable {
 8         // 参数代理
 9         if (invocation.getTarget() instanceof ParameterHandler) {
10             System.out.println("ParameterHandler");
11             // 自动添加操作员信息
12             autoAddOperatorInfo(invocation);
13         }
14         return invocation.proceed();
15     }
16 
17     @Override
18     public Object plugin(Object target) {
19         return Plugin.wrap(target, this);
20     }
21 
22     @Override
23     public void setProperties(Properties properties) {
24 
25     }
26 
27     /**
28      * 自动添加操作员信息
29      *
30      * @param invocation 代理对象
31      * @throws Throwable 异常
32      */
33     private void autoAddOperatorInfo(Invocation invocation) throws Throwable {
34         System.out.println("autoInsertCreatorInfo");
35         // 获取代理的参数对象ParameterHandler
36         ParameterHandler ph = (ParameterHandler) invocation.getTarget();
37         // 通过MetaObject获取ParameterHandler的反射内容
38         MetaObject metaObject = MetaObject.forObject(ph,
39                 SystemMetaObject.DEFAULT_OBJECT_FACTORY,
40                 SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
41                 new DefaultReflectorFactory());
42         // 通过MetaObject反射的内容获取MappedStatement
43         MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("mappedStatement");
44         // 当sql类型为INSERT或UPDATE时,自动插入操作员信息
45         if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT ||
46                 mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE) {
47             // 获取参数对象
48             Object obj = ph.getParameterObject();
49             if (null != obj) {
50                 // 通过反射获取参数对象的属性
51                 Field[] fields = obj.getClass().getDeclaredFields();
52                 // 遍历参数对象的属性
53                 for (Field f : fields) {
54                     // 如果sql是INSERT,且存在createdAt属性
55                     if ("createdAt".equals(f.getName()) && mappedStatement.getSqlCommandType() == SqlCommandType.INSERT) {
56                         // 设置允许访问反射属性
57                         f.setAccessible(true);
58                         // 如果没有设置createdAt属性,则自动为createdAt属性添加当前的时间
59                         if (null == f.get(obj)) {
60                             // 设置createdAt属性为当前时间
61                             f.set(obj, LocalDateTime.now());
62                         }
63                     }
64                     // 如果sql是INSERT,且存在createdBy属性
65                     if ("createdBy".equals(f.getName()) && mappedStatement.getSqlCommandType() == SqlCommandType.INSERT) {
66                         // 设置允许访问反射属性
67                         f.setAccessible(true);
68                         // 如果没有设置createdBy属性,则自动为createdBy属性添加当前登录的人员
69                         if (null == f.get(obj)) {
70                             // 设置createdBy属性为当前登录的人员
71                             f.set(obj, 0);
72                         }
73                     }
74                     // sql为INSERT或UPDATE时均需要设置updatedAt属性
75                     if ("updatedAt".equals(f.getName())) {
76                         f.setAccessible(true);
77                         if (null == f.get(obj)) {
78                             f.set(obj, LocalDateTime.now());
79                         }
80                     }
81                     // sql为INSERT或UPDATE时均需要设置updatedBy属性
82                     if ("updatedBy".equals(f.getName())) {
83                         f.setAccessible(true);
84                         if (null == f.get(obj)) {
85                             f.set(obj, 0);
86                         }
87                     }
88                 }
89 
90                 // 通过反射获取ParameterHandler的parameterObject属性
91                 Field parameterObject = ph.getClass().getDeclaredField("parameterObject");
92                 // 设置允许访问parameterObject属性
93                 parameterObject.setAccessible(true);
94                 // 将上面设置的新参数对象设置到ParameterHandler的parameterObject属性
95                 parameterObject.set(ph, obj);
96             }
97         }
98     }
99 }

        拦截器的接口实现参考前文,这里着重介绍autoAddOperatorInfo方法里的相关类。

        1.ParameterHandler

        接口源码:

1 public interface ParameterHandler {
2     Object getParameterObject();
3     void setParameters(PreparedStatement var1) throws SQLException;
4 }

        提供两个方法:

        getParameterObject是获取参数对象,可能存在null,需要注意null指针。

        setParameters是控制如何设置SQL参数,即sql语句中配置的java对象和jdbc类型对应的关系,例如#{id,jdbcType=INTEGER},id默认类型是javaType=class java.lang.Integer。

        该接口有一个默认的实现类,源码如下:

 1 public class DefaultParameterHandler implements ParameterHandler {
 2     private final TypeHandlerRegistry typeHandlerRegistry;
 3     private final MappedStatement mappedStatement;
 4     private final Object parameterObject;
 5     private final BoundSql boundSql;
 6     private final Configuration configuration;
 7 
 8     public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
 9         this.mappedStatement = mappedStatement;
10         this.configuration = mappedStatement.getConfiguration();
11         this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
12         this.parameterObject = parameterObject;
13         this.boundSql = boundSql;
14     }
15 
16     public Object getParameterObject() {
17         return this.parameterObject;
18     }
19 
20     public void setParameters(PreparedStatement ps) {
21         ErrorContext.instance().activity("setting parameters").object(this.mappedStatement.getParameterMap().getId());
22         List<ParameterMapping> parameterMappings = this.boundSql.getParameterMappings();
23         if (parameterMappings != null) {
24             for(int i = 0; i < parameterMappings.size(); ++i) {
25                 ParameterMapping parameterMapping = (ParameterMapping)parameterMappings.get(i);
26                 if (parameterMapping.getMode() != ParameterMode.OUT) {
27                     String propertyName = parameterMapping.getProperty();
28                     Object value;
29                     if (this.boundSql.hasAdditionalParameter(propertyName)) {
30                         value = this.boundSql.getAdditionalParameter(propertyName);
31                     } else if (this.parameterObject == null) {
32                         value = null;
33                     } else if (this.typeHandlerRegistry.hasTypeHandler(this.parameterObject.getClass())) {
34                         value = this.parameterObject;
35                     } else {
36                         MetaObject metaObject = this.configuration.newMetaObject(this.parameterObject);
37                         value = metaObject.getValue(propertyName);
38                     }
39 
40                     TypeHandler typeHandler = parameterMapping.getTypeHandler();
41                     JdbcType jdbcType = parameterMapping.getJdbcType();
42                     if (value == null && jdbcType == null) {
43                         jdbcType = this.configuration.getJdbcTypeForNull();
44                     }
45 
46                     try {
47                         typeHandler.setParameter(ps, i + 1, value, jdbcType);
48                     } catch (SQLException | TypeException var10) {
49                         throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + var10, var10);
50                     }
51                 }
52             }
53         }
54 
55     }
56 }

        通过DefaultParameterHandler实现类我们知道通过ParameterHandler可以获取到哪些属性和方法,其中包括我们下面一个重要的类MappedStatement。

        2.MappedStatement

        MyBatis的mapper文件中的每个select/update/insert/delete标签会被解析器解析成一个对应的MappedStatement对象,也就是一个MappedStatement对象描述一条SQL语句。MappedStatement对象属性如下:

 1     // mapper配置文件名
 2     private String resource;
 3     // mybatis的全局信息,如jdbc
 4     private Configuration configuration;
 5     // 节点的id属性加命名空间,如:com.example.mybatis.dao.UserMapper.selectByExample
 6     private String id;
 7     private Integer fetchSize;
 8     private Integer timeout;
 9     private StatementType statementType;
10     private ResultSetType resultSetType;
11     private SqlSource sqlSource;
12     private Cache cache;
13     private ParameterMap parameterMap;
14     private List<ResultMap> resultMaps;
15     private boolean flushCacheRequired;
16     private boolean useCache;
17     private boolean resultOrdered;
18     // sql语句的类型:select、update、delete、insert
19     private SqlCommandType sqlCommandType;
20     private KeyGenerator keyGenerator;
21     private String[] keyProperties;
22     private String[] keyColumns;
23     private boolean hasNestedResultMaps;
24     private String databaseId;
25     private Log statementLog;
26     private LanguageDriver lang;
27     private String[] resultSets;

        在本例中通过MappedStatement对象的sqlCommandType来判断当前的sql类型是insert、update来进行下一步的操作。

四、通过StatementHandler改写SQL

        StatementHandler是用于封装JDBC Statement操作,负责对JDBC Statement的操作,如设置参数,并将Statement结果集转换成List集合。

        实现代码如下:

        删除注解标记

@Target({ElementType.METHOD})  //表示注解的使用范围
@Retention(RetentionPolicy.RUNTIME) //注解的保存时间
@Documented    //文档显示
public @interface DeletedAt {
    boolean has() default true;
}

        Dao层添加删除注解,为false时不添加删除标志

1 @Mapper
2 public interface AdminProjectDao {
3     @DeletedAt(has = false)
4     List<AdminProjectPo> selectProjects(AdminProjectPo po);
5 }

        拦截器通过删除注解标记判断是否添加删除标志

 1 @Component
 2 @Intercepts({
 3         @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
 4 })
 5 public class MyBatisInterceptor implements Interceptor {
 6     @Override
 7     public Object intercept(Invocation invocation) throws Throwable {
 8         if (invocation.getTarget() instanceof StatementHandler) {
 9             System.out.println("StatementHandler");
10             checkHasDeletedAtField(invocation);
11         }
12         return invocation.proceed();
13     }
14 
15     @Override
16     public Object plugin(Object target) {
17         return Plugin.wrap(target, this);
18     }
19 
20     @Override
21     public void setProperties(Properties properties) {
22 
23     }
24 
25     /**
26      * 检查查询是否需要添加删除标志字段
27      *
28      * @param invocation 代理对象
29      * @throws Throwable 异常
30      */
31     private void checkHasDeletedAtField(Invocation invocation) throws Throwable {
32         System.out.println("checkHasDeletedAtField");
33         StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
34         // 通过MetaObject访问对象的属性
35         MetaObject metaObject = MetaObject.forObject(
36                 statementHandler,
37                 SystemMetaObject.DEFAULT_OBJECT_FACTORY,
38                 SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
39                 new DefaultReflectorFactory());
40         // 获取成员变量mappedStatement
41         MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
42         // 如果sql类型是查询
43         if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT) {
44             // 获取删除注解标志
45             DeletedAt annotation = null;
46             String id = mappedStatement.getId();
47             String className = id.substring(0, id.lastIndexOf("."));
48             String methodName = id.substring(id.lastIndexOf(".") + 1);
49             Class<?> aClass = Class.forName(className);
50             Method[] declaredMethods = aClass.getDeclaredMethods();
51             for (Method declaredMethod : declaredMethods) {
52                 declaredMethod.setAccessible(true);
53                 //方法名相同,并且注解是DeletedAt
54                 if (methodName.equals(declaredMethod.getName()) && declaredMethod.isAnnotationPresent(DeletedAt.class)) {
55                     annotation = declaredMethod.getAnnotation(DeletedAt.class);
56                 }
57             }
58             // 如果注解不存在或者注解为true(默认为true) 则为mysql语句增加删除标志
59             if (annotation == null || annotation.has()) {
60                 BoundSql boundSql = statementHandler.getBoundSql();
61                 //获取到原始sql语句
62                 String sql = boundSql.getSql();
63                 //通过反射修改sql语句
64                 Field field = boundSql.getClass().getDeclaredField("sql");
65                 field.setAccessible(true);
66                 String newSql = sql.replaceAll("9=9", "9=9 and deleted_at is null ");
67                 field.set(boundSql, newSql);
68             }
69         }
70     }
71 }

        在SQL语句替换上需要能识别到要被替换的内容,因此在xml的sql语句中加入特殊标志"9=9",该标志不影响原来SQL的执行结果,不同的过滤条件可以设置不同的标志,是一个比较巧妙的替换方式。

posted @ 2021-06-16 18:12  飘梧  阅读(336)  评论(0编辑  收藏  举报