评论

收藏

[Java] Mybatis Interceptor 拦截器的实现

编程语言 编程语言 发布于:2021-10-06 15:47 | 阅读数:350 | 评论:0

这篇文章主要介绍了Mybatis Interceptor 拦截器的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变mybatis的默认行为(诸如sql重写之类的),由于插件会深入到mybatis的核心,因此在编写自己的插件前最好了解下它的原理,以便写出安全高效的插件。
拦截器(interceptor)在 mybatis 中被当做插件(plugin)对待,官方文档提供了 executor,parameterhandler,resultsethandler,statementhandler 共4种,并且提示“这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 mybatis 发行包中的源代码”。
拦截器的使用场景主要是更新数据库的通用字段,分库分表,加解密等的处理。
1. interceptor
拦截器均需要实现该 org.apache.ibatis.plugin.interceptor 接口。
2. intercepts 拦截器
@intercepts({
  @signature(type = executor.class, method = "update", args = {mappedstatement.class, object.class})
})
拦截器的使用需要查看每一个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 类,即包含表公共字段,比如创建、更新操作对象和时间的基类等,在编写代码时尽量依据该对象来操作,会简单很多。该对象的判断使用
object parameter = invocation.getargs()[1];
if (parameter instanceof baseentity) {
  baseentity entity = (baseentity) parameter;
}
即可,根据语句执行类型选择对应字段的赋值。
如果参数不是实体,而且具体的参数,那么 mybatis 也做了一些处理,比如 @param("name") string name 类型的参数,会被包装成 map 接口的实现来处理,即使是原始的 map 也是如此。使用
object parameter = invocation.getargs()[1];
if (parameter instanceof map) {
  map map = (map) parameter;
}
即可,对具体统一的参数进行赋值。
4. sqlcommandtype 命令类型
executor 提供的方法中,update 包含了 新增,修改和删除类型,无法直接区分,需要借助 mappedstatement 类的属性 sqlcommandtype 来进行判断,该类包含了所有的操作类型
public enum sqlcommandtype {
 unknown, insert, update, delete, select, flush;
}
毕竟新增和修改的场景,有些参数是有区别的,比如创建时间和更新时间,update 时是无需兼顾创建时间字段的。
mappedstatement ms = (mappedstatement) invocation.getargs()[0];
sqlcommandtype commandtype = ms.getsqlcommandtype();
5. 实例
自己编写的小项目中,需要统一给数据库字段属性赋值:
public class baseentity {
  private int id;
  private int creator;
  private int updater;
  private long createtime;
  private long updatetime;
}
dao 操作使用了实体和参数的方式,个人建议还是统一使用实体比较简单,易读。
使用实体:
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);
完整的例子:
package com.github.zhgxun.talk.common.plugin;
 
import com.github.zhgxun.talk.common.util.dateutil;
import com.github.zhgxun.talk.common.util.userutil;
import com.github.zhgxun.talk.entity.baseentity;
import com.github.zhgxun.talk.entity.userentity;
import lombok.extern.slf4j.slf4j;
import org.apache.ibatis.executor.executor;
import org.apache.ibatis.mapping.mappedstatement;
import org.apache.ibatis.mapping.sqlcommandtype;
import org.apache.ibatis.plugin.interceptor;
import org.apache.ibatis.plugin.intercepts;
import org.apache.ibatis.plugin.invocation;
import org.apache.ibatis.plugin.plugin;
import org.apache.ibatis.plugin.signature;
import org.springframework.stereotype.component;
 
import java.util.map;
import java.util.properties;
 
/**
 * 全局拦截数据库创建和更新
 * <p>
 * signature 对应 invocation 构造器, type 为 invocation.object, method 为 invocation.method, args 为 invocation.object[]
 * method 对应的 update 包括了最常用的 insert/update/delete 三种操作, 因此 update 本身无法直接判断sql为何种执行过程
 * args 包含了其余多有的操作信息, 按数组进行存储, 不同的拦截方式有不同的参数顺序, 具体看type接口的方法签名, 然后根据签名解析, 参见官网
 *
 * @link http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins 插件
 * <p>
 * mappedstatement 包括了sql具体操作类型, 需要通过该类型判断当前sql执行过程
 */
@component
@intercepts({
  @signature(type = executor.class, method = "update", args = {mappedstatement.class, object.class})
})
@slf4j
public class normalplugin implements interceptor {
 
  @override
  @suppresswarnings("unchecked")
  public object intercept(invocation invocation) throws throwable {
  // 根据签名指定的args顺序获取具体的实现类
  // 1. 获取mappedstatement实例, 并获取当前sql命令类型
  mappedstatement ms = (mappedstatement) invocation.getargs()[0];
  sqlcommandtype commandtype = ms.getsqlcommandtype();
 
  // 2. 获取当前正在被操作的类, 有可能是java bean, 也可能是普通的操作对象, 比如普通的参数传递
  // 普通参数, 即是 @param 包装或者原始 map 对象, 普通参数会被 mybatis 包装成 map 对象
  // 即是 org.apache.ibatis.binding.mappermethod$parammap
  object parameter = invocation.getargs()[1];
  // 获取拦截器指定的方法类型, 通常需要拦截 update
  string methodname = invocation.getmethod().getname();
  log.info("normalplugin, methodname; {}, commandtype: {}", methodname, commandtype);
 
  // 3. 获取当前用户信息
  userentity userentity = userutil.getcurrentuser();
  // 默认测试参数值
  int creator = 2, updater = 3;
 
  if (parameter instanceof baseentity) {
    // 4. 实体类
    baseentity entity = (baseentity) parameter;
    if (userentity != null) {
    creator = entity.getcreator();
    updater = entity.getupdater();
    }
    if (methodname.equals("update")) {
    if (commandtype.equals(sqlcommandtype.insert)) {
      entity.setcreator(creator);
      entity.setupdater(updater);
      entity.setcreatetime(dateutil.gettimestamp());
      entity.setupdatetime(dateutil.gettimestamp());
    } else if (commandtype.equals(sqlcommandtype.update)) {
      entity.setupdater(updater);
      entity.setupdatetime(dateutil.gettimestamp());
    }
    }
  } else if (parameter instanceof map) {
    // 5. @param 等包装类
    // 更新时指定某些字段的最新数据值
    if (commandtype.equals(sqlcommandtype.update)) {
    // 遍历参数类型, 检查目标参数值是否存在对象中, 该方式需要应用编写有一些统一的规范
    // 否则均统一为实体对象, 就免去该重复操作
    map map = (map) parameter;
    if (map.containskey("creator")) {
      map.put("creator", creator);
    }
    if (map.containskey("updatetime")) {
      map.put("updatetime", dateutil.gettimestamp());
    }
    }
  }
  // 6. 均不是需要被拦截的类型, 不做操作
  return invocation.proceed();
  }
 
  @override
  public object plugin(object target) {
  return plugin.wrap(target, this);
  }
 
  @override
  public void setproperties(properties properties) {
  }
}
6. 感受
其它几种类型,后面在看,尤其是分页。
在编写代码的过程中,有时候还是需要先知道对象的类型,比如 object.class 跟 interface 一样,很多时候仅仅代表一种数据类型,需要明确知道后再进行操作。
@param 标识的参数其实会被 mybatis 封装成 org.apache.ibatis.binding.mappermethod$parammap 类型,一开始我就是使用
for (field field:parameter.getclass().getdeclaredfields()) {
 
}
的方式获取,以为这些都是对象的属性,通过反射获取并修改即可,实际上发现对象不存在这些属性,但是打印出的信息中,明确有这些字段的,网上参考一些信息后,才知道这是一个 map 类型,问题才迎刃而解。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家
原文链接:https://segmentfault.com/a/1190000017393523

关注下面的标签,发现更多相似文章