温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Mybatis中实现一个Interceptor 拦截器

发布时间:2021-05-24 18:17:42 来源:亿速云 阅读:383 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关如何在Mybatis中实现一个Interceptor 拦截器,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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()) {

}

关于如何在Mybatis中实现一个Interceptor 拦截器就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI