mybatis拦截器:实现拦截update语句插入列值
1、修改sql的时机
在预编译SQL(prepare方法)前加入修改的逻辑。
可以对sql处理也可以对映射类做处理(本例是对映射类做处理)。
2、准备的xml文件
mybatis-config.xml
<?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="拦截器的完整包名"/>
</plugins>
</configuration>
3、添加的拦截器类
在 Update 语句中,自动填充当前 updateTime 时间。
@Slf4j
@Component
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class UpdateTimeInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
/* 先拦截到RoutingStatementHandler,里面有个StatementHandler类型的delegate变量,
* 其实现类是BaseStatementHandler,然后就到BaseStatementHandler的成员变量mappedStatement。
*/
MetaObject metaObject = MetaObject.forObject(
statementHandler,
SystemMetaObject.DEFAULT_OBJECT_FACTORY,
SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
new DefaultReflectorFactory()
);
MappedStatement mappedStatement =
(MappedStatement) metaObject.getValue("delegate.mappedStatement");
// sql语句类型:
// UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH、
// update, SqlCommandType 是个 enum
String sqlCommandType = mappedStatement.getSqlCommandType().toString();
BoundSql boundSql = statementHandler.getBoundSql();
//得到的映射类和sql
Object obj = boundSql.getParameterObject();
String sql = boundSql.getSql();
//在update语句的时候加入updateTime变量,如果存在被覆盖,不存在加入
if (sqlCommandType.equals("UPDATE")) {
ReflectUtil.setFieldValue(obj, "updateTime", LocalDateTime.now());
}
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
}
Ref