MyBatis自定义拦截器
Mybatis允许你在已经映射语句的执行过程中为某一点进行拦截调用。但是并不是对所有的方法都可以进行这种拦截处理,允许使用插件进行的拦截类如下,具体要拦截该类中哪一个方法则需要关注下mybatis的源码,去指定拦截时的方法入参:支持的拦截类如下:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) ParameterHandler (getParameterObject, setParameters) ResultSetHandler (handleResultSets, handleOutputParameters) StatementHandler (prepare, parameterize, batch, update, query)
自定义拦截器
实现在新增/更新操作时动态为sql注入creationDate以及lastUpdateDate时间字段
定义拦截器时运行时注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CreateTime {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CreateTime {
String value() default "";
}
实体类
@Data
@Table(name = "`demo`")
public class Demo implements Serializable {
/**
* 主键
*/
@Id
@JSONField(serializeUsing = ToStringSerializer.class)
@GeneratedValue(generator = "JDBC")
private Long id;
/**
* 名称
*/
private String name;
/**
* 创建时间
*/
@CreateTime
private Date createdTime;
private static final long serialVersionUID = 1L;
}
拦截器的核心代码
@Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
public class CustomInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// 获取 SQL 命令
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
// 获取参数
Object parameter = invocation.getArgs()[1];
// 获取私有成员变量
Field[] declaredFields = parameter.getClass().getDeclaredFields();
for (Field field : declaredFields) {
if (field.getAnnotation(CreateTime.class) != null) {
if (SqlCommandType.INSERT.equals(sqlCommandType)) { // insert 语句插入 createTime
field.setAccessible(true);
field.set(parameter, new Date());
}
}
if (field.getAnnotation(UpdateTime.class) != null) { // insert 或 update 语句插入 updateTime
if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
field.setAccessible(true);
field.set(parameter, new Date());
}
}
}
return invocation.proceed();
}
}
Mybatis配置文件中添加插件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.wueasy.demo.plugin.CustomInterceptor">
</plugin>
</plugins>
</configuration>