mybatis 记录sql执行前后的数据变化
此方法并不完善,只是简单记录。
以update语句为例。通过mybatis的拦截器拦截sql,然后提取出表名和条件,查询出来原始数据,然后保存数据和update语句。这样就可以对比原始数据,和执行sql的改变的数据。
delete和insert 只记录sql,直接插入记录中。
注意:如果记录要插入数据库,那么记录表要记的忽略。不然会一直调用
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.fastrun.common.core.domain.model.LoginUser;
import com.fastrun.common.utils.NumberUtils;
import com.fastrun.common.utils.SecurityUtils;
import com.fastrun.common.utils.spring.SpringUtils;
import com.fastrun.common.utils.sql.SqlUtil;
import com.fastrun.system.domain.SysOprLog;
import com.fastrun.system.mapper.PlugMapper;
import com.fastrun.system.service.impl.SysOprLogServiceImpl;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.metaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;
@Component
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@SuppressWarnings({"unchecked", "rawtypes"})
public class MybatisInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
// 获取xml中的一个select/update/insert/delete节点,是一条SQL语句
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = null;
if (invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
}
// BoundSql就是封装myBatis最终产生的sql类
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
// 获取节点的配置
Configuration configuration = mappedStatement.getConfiguration();
// 获取到最终的sql语句
String sql = showSql(configuration, boundSql);
String tableName = SqlUtil.getTableNames(boundSql.getSql()).get(0);
String[] sqlArr = sql.split("where");
String where = "";
if (sqlArr.length == 2) {
where = sqlArr[1];
}
if (!isIgnoreTable(tableName)) {
Long userId = null;
try {
Authentication authentication = SecurityUtils.getAuthentication();
if (null != authentication) {
Object loginUser = authentication.getPrincipal();
if (loginUser instanceof LoginUser) {
userId = ((LoginUser) loginUser).getUserId();
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (NumberUtils.isPositive(userId)) {
String cmdType = mappedStatement.getSqlCommandType().name();
SysOprLog oprLog = new SysOprLog();
if ("update".equalsIgnoreCase(cmdType)) {
List
评论列表(0条)