经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
Mybatis Interceptor 拦截器的实现
来源:jb51  时间:2018/12/18 9:16:48  对本文有异议

Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最好了解下它的原理,以便写出安全高效的插件。

拦截器(Interceptor)在 Mybatis 中被当做插件(plugin)对待,官方文档提供了 Executor,ParameterHandler,ResultSetHandler,StatementHandler 共4种,并且提示“这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 MyBatis 发行包中的源代码”。

拦截器的使用场景主要是更新数据库的通用字段,分库分表,加解密等的处理。

1. Interceptor

拦截器均需要实现该 org.apache.ibatis.plugin.Interceptor 接口。

2. Intercepts 拦截器

  1. @Intercepts({
  2. @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
  3. })

拦截器的使用需要查看每一个type所提供的方法参数。

Signature 对应 Invocation 构造器,type 为 Invocation.Object,method 为 Invocation.Method,args 为 Invocation.Object[]。

method 对应的 update 包括了最常用的 insert/update/delete 三种操作,因此 update 本身无法直接判断sql为何种执行过程。

args 包含了其余所有的操作信息, 按数组进行存储, 不同的拦截方式有不同的参数顺序, 具体看type接口的方法签名, 然后根据签名解析。

3. Object 对象类型

args 参数列表中,Object.class 是特殊的对象类型。如果有数据库统一的实体 Entity 类,即包含表公共字段,比如创建、更新操作对象和时间的基类等,在编写代码时尽量依据该对象来操作,会简单很多。该对象的判断使用

  1. Object parameter = invocation.getArgs()[1];
  2. if (parameter instanceof BaseEntity) {
  3. BaseEntity entity = (BaseEntity) parameter;
  4. }

即可,根据语句执行类型选择对应字段的赋值。

如果参数不是实体,而且具体的参数,那么 Mybatis 也做了一些处理,比如 @Param("name") String name 类型的参数,会被包装成 Map 接口的实现来处理,即使是原始的 Map 也是如此。使用

  1. Object parameter = invocation.getArgs()[1];
  2. if (parameter instanceof Map) {
  3. Map map = (Map) parameter;
  4. }

即可,对具体统一的参数进行赋值。

4. SqlCommandType 命令类型

Executor 提供的方法中,update 包含了 新增,修改和删除类型,无法直接区分,需要借助 MappedStatement 类的属性 SqlCommandType 来进行判断,该类包含了所有的操作类型

  1. public enum SqlCommandType {
  2. UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH;
  3. }

毕竟新增和修改的场景,有些参数是有区别的,比如创建时间和更新时间,update 时是无需兼顾创建时间字段的。

  1. MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
  2. SqlCommandType commandType = ms.getSqlCommandType();

5. 实例

自己编写的小项目中,需要统一给数据库字段属性赋值:

  1. public class BaseEntity {
  2. private int id;
  3. private int creator;
  4. private int updater;
  5. private Long createTime;
  6. private Long updateTime;
  7. }

dao 操作使用了实体和参数的方式,个人建议还是统一使用实体比较简单,易读。

使用实体:

  1. int add(BookEntity entity);

使用参数:

复制代码 代码如下:
int update(@Param("id") int id, @Param("url") String url, @Param("description") String description, @Param("playCount") int playCount, @Param("creator") int creator, @Param("updateTime") long updateTime);

完整的例子:

  1. package com.github.zhgxun.talk.common.plugin;
  2.  
  3. import com.github.zhgxun.talk.common.util.DateUtil;
  4. import com.github.zhgxun.talk.common.util.UserUtil;
  5. import com.github.zhgxun.talk.entity.BaseEntity;
  6. import com.github.zhgxun.talk.entity.UserEntity;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.ibatis.executor.Executor;
  9. import org.apache.ibatis.mapping.MappedStatement;
  10. import org.apache.ibatis.mapping.SqlCommandType;
  11. import org.apache.ibatis.plugin.Interceptor;
  12. import org.apache.ibatis.plugin.Intercepts;
  13. import org.apache.ibatis.plugin.Invocation;
  14. import org.apache.ibatis.plugin.Plugin;
  15. import org.apache.ibatis.plugin.Signature;
  16. import org.springframework.stereotype.Component;
  17.  
  18. import java.util.Map;
  19. import java.util.Properties;
  20.  
  21. /**
  22. * 全局拦截数据库创建和更新
  23. * <p>
  24. * Signature 对应 Invocation 构造器, type 为 Invocation.Object, method 为 Invocation.Method, args 为 Invocation.Object[]
  25. * method 对应的 update 包括了最常用的 insert/update/delete 三种操作, 因此 update 本身无法直接判断sql为何种执行过程
  26. * args 包含了其余多有的操作信息, 按数组进行存储, 不同的拦截方式有不同的参数顺序, 具体看type接口的方法签名, 然后根据签名解析, 参见官网
  27. *
  28. * @link http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins 插件
  29. * <p>
  30. * MappedStatement 包括了SQL具体操作类型, 需要通过该类型判断当前sql执行过程
  31. */
  32. @Component
  33. @Intercepts({
  34. @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
  35. })
  36. @Slf4j
  37. public class NormalPlugin implements Interceptor {
  38.  
  39. @Override
  40. @SuppressWarnings("unchecked")
  41. public Object intercept(Invocation invocation) throws Throwable {
  42. // 根据签名指定的args顺序获取具体的实现类
  43. // 1. 获取MappedStatement实例, 并获取当前SQL命令类型
  44. MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
  45. SqlCommandType commandType = ms.getSqlCommandType();
  46.  
  47. // 2. 获取当前正在被操作的类, 有可能是Java Bean, 也可能是普通的操作对象, 比如普通的参数传递
  48. // 普通参数, 即是 @Param 包装或者原始 Map 对象, 普通参数会被 Mybatis 包装成 Map 对象
  49. // 即是 org.apache.ibatis.binding.MapperMethod$ParamMap
  50. Object parameter = invocation.getArgs()[1];
  51. // 获取拦截器指定的方法类型, 通常需要拦截 update
  52. String methodName = invocation.getMethod().getName();
  53. log.info("NormalPlugin, methodName; {}, commandType: {}", methodName, commandType);
  54.  
  55. // 3. 获取当前用户信息
  56. UserEntity userEntity = UserUtil.getCurrentUser();
  57. // 默认测试参数值
  58. int creator = 2, updater = 3;
  59.  
  60. if (parameter instanceof BaseEntity) {
  61. // 4. 实体类
  62. BaseEntity entity = (BaseEntity) parameter;
  63. if (userEntity != null) {
  64. creator = entity.getCreator();
  65. updater = entity.getUpdater();
  66. }
  67. if (methodName.equals("update")) {
  68. if (commandType.equals(SqlCommandType.INSERT)) {
  69. entity.setCreator(creator);
  70. entity.setUpdater(updater);
  71. entity.setCreateTime(DateUtil.getTimeStamp());
  72. entity.setUpdateTime(DateUtil.getTimeStamp());
  73. } else if (commandType.equals(SqlCommandType.UPDATE)) {
  74. entity.setUpdater(updater);
  75. entity.setUpdateTime(DateUtil.getTimeStamp());
  76. }
  77. }
  78. } else if (parameter instanceof Map) {
  79. // 5. @Param 等包装类
  80. // 更新时指定某些字段的最新数据值
  81. if (commandType.equals(SqlCommandType.UPDATE)) {
  82. // 遍历参数类型, 检查目标参数值是否存在对象中, 该方式需要应用编写有一些统一的规范
  83. // 否则均统一为实体对象, 就免去该重复操作
  84. Map map = (Map) parameter;
  85. if (map.containsKey("creator")) {
  86. map.put("creator", creator);
  87. }
  88. if (map.containsKey("updateTime")) {
  89. map.put("updateTime", DateUtil.getTimeStamp());
  90. }
  91. }
  92. }
  93. // 6. 均不是需要被拦截的类型, 不做操作
  94. return invocation.proceed();
  95. }
  96.  
  97. @Override
  98. public Object plugin(Object target) {
  99. return Plugin.wrap(target, this);
  100. }
  101.  
  102. @Override
  103. public void setProperties(Properties properties) {
  104. }
  105. }

6. 感受

其它几种类型,后面在看,尤其是分页。

在编写代码的过程中,有时候还是需要先知道对象的类型,比如 Object.class 跟 Interface 一样,很多时候仅仅代表一种数据类型,需要明确知道后再进行操作。

@Param 标识的参数其实会被 Mybatis 封装成 org.apache.ibatis.binding.MapperMethod$ParamMap 类型,一开始我就是使用

  1. for (Field field:parameter.getClass().getDeclaredFields()) {
  2.  
  3. }

的方式获取,以为这些都是对象的属性,通过反射获取并修改即可,实际上发现对象不存在这些属性,但是打印出的信息中,明确有这些字段的,网上参考一些信息后,才知道这是一个 Map 类型,问题才迎刃而解。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号