拦截器(Interceptor)在 Mybatis 中被当作插件(plugin)对待,官方文档提供了 Executor(拦截执行器的方法),ParameterHandler(拦截参数的处理),ResultSetHandler(拦截结果集的处理),StatementHandler(拦截Sql语法构建的处理) 共4种,而且提示“这些类中方法的细节能够经过查看每一个方法的签名来发现,或者直接查看 MyBatis 发行包中的源代码”。html
拦截器的使用场景主要是更新数据库的通用字段,分库分表,加解密等的处理。java
拦截器均须要实现该 org.apache.ibatis.plugin.Interceptor
接口。git
@Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) })
拦截器的使用须要查看每个type所提供的方法参数。github
Signature 对应 Invocation 构造器,type 为 Invocation.Object,method 为 Invocation.Method,args 为 Invocation.Object[]。spring
method 对应的 update 包括了最经常使用的 insert/update/delete 三种操做,所以 update 自己没法直接判断sql为什么种执行过程。sql
args 包含了其他全部的操做信息, 按数组进行存储, 不一样的拦截方式有不一样的参数顺序, 具体看type接口的方法签名, 而后根据签名解析。数据库
args 参数列表中,Object.class 是特殊的对象类型。若是有数据库统一的实体 Entity 类,即包含表公共字段,好比建立、更新操做对象和时间的基类等,在编写代码时尽可能依据该对象来操做,会简单不少。该对象的判断使用apache
Object parameter = invocation.getArgs()[1]; if (parameter instanceof BaseEntity) { BaseEntity entity = (BaseEntity) parameter; }
便可,根据语句执行类型选择对应字段的赋值。数组
若是参数不是实体,并且具体的参数,那么 Mybatis 也作了一些处理,好比 @Param("name") String name
类型的参数,会被包装成 Map
接口的实现来处理,即便是原始的 Map
也是如此。使用mybatis
Object parameter = invocation.getArgs()[1]; if (parameter instanceof Map) { Map map = (Map) parameter; }
便可,对具体统一的参数进行赋值。
Executor
提供的方法中,update
包含了 新增,修改和删除类型,没法直接区分,须要借助 MappedStatement
类的属性 SqlCommandType
来进行判断,该类包含了全部的操做类型
public enum SqlCommandType { UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH; }
毕竟新增和修改的场景,有些参数是有区别的,好比建立时间和更新时间,update
时是无需兼顾建立时间字段的。
MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; SqlCommandType commandType = ms.getSqlCommandType();
本身编写的小项目中,须要统一给数据库字段属性赋值:
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) { } }
其它几种类型,后面在看,尤为是分页。
在编写代码的过程当中,有时候仍是须要先知道对象的类型,好比 Object.class 跟 Interface 同样,不少时候仅仅表明一种数据类型,须要明确知道后再进行操做。
@Param
标识的参数其实会被 Mybatis 封装成 org.apache.ibatis.binding.MapperMethod$ParamMap
类型,一开始我就是使用
for (Field field:parameter.getClass().getDeclaredFields()) { }
的方式获取,觉得这些都是对象的属性,经过反射获取并修改便可,实际上发现对象不存在这些属性,可是打印出的信息中,明确有这些字段的,网上参考一些信息后,才知道这是一个 Map
类型,问题才迎刃而解。
可参考MyBatis拦截器原理探究。