拦截mybatis(mybatis-plus)SQL

2023-10-29

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
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.apache.ibatis.session.Configuration;
import org.apache.shiro.SecurityUtils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * mybatis拦截器,自动注入创建人、创建时间、修改人、修改时间
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Autowired
    private ILogDelService logDelService;

    @Autowired
    private ILogUpService logUpService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        log.debug("------sqlId------" + sqlId);
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        BoundSql boundSql = mappedStatement.getBoundSql(parameter); // BoundSql就是封装myBatis最终产生的sql类
        Configuration configuration = mappedStatement.getConfiguration(); // 获取节点的配置
        String sql = SplicSqlUtils.getSql(configuration, boundSql, sqlId); // 获取到最终的sql语句

        if (parameter == null) {
            return invocation.proceed();
        }
        if (SqlCommandType.INSERT == sqlCommandType) {
            LoginUser sysUser = this.getLoginUser();
            Field[] fields = oConvertUtils.getAllFields(parameter);
            for (Field field : fields) {
                log.debug("------field.name------" + field.getName());
                try {
                    if ("createBy".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createBy = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createBy == null || local_createBy.equals("")) {
                            if (sysUser != null) {
                                // 登录人账号
                                field.setAccessible(true);
                                field.set(parameter, sysUser.getUsername());
                                field.setAccessible(false);
                            }
                        }
                    }
                    // 注入创建时间
                    if ("createTime".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createDate = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createDate == null || local_createDate.equals("")) {
                            field.setAccessible(true);
                            field.set(parameter, new Date());
                            field.setAccessible(false);
                        }
                    }
                    //注入部门编码
                    if ("sysOrgCode".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_sysOrgCode = field.get(parameter);
                        field.setAccessible(false);
                        if (local_sysOrgCode == null || local_sysOrgCode.equals("")) {
                            // 获取登录用户信息
                            if (sysUser != null) {
                                field.setAccessible(true);
                                field.set(parameter, sysUser.getOrgCode());
                                field.setAccessible(false);
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {
            // 添加修改记录
            LogUp logUp = new LogUp();
            logUp.setSqlStr(sql);
            logUp.setCreateTime(DateUtils.getDate());
            logUp.setIsUsed(0);
            logUpService.save(logUp);

            LoginUser sysUser = this.getLoginUser();
            Field[] fields;
            if (parameter instanceof ParamMap) {
                ParamMap<?> p = (ParamMap<?>) parameter;
                //update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
                if (p.containsKey("et")) {
                    parameter = p.get("et");
                } else {
                    parameter = p.get("param1");
                }
                //update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-

                //update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
                if (parameter == null) {
                    return invocation.proceed();
                }
                //update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-

                fields = oConvertUtils.getAllFields(parameter);
            } else {
                fields = oConvertUtils.getAllFields(parameter);
            }

            for (Field field : fields) {
                log.debug("------field.name------" + field.getName());
                try {
                    if ("updateBy".equals(field.getName())) {
                        //获取登录用户信息
                        if (sysUser != null) {
                            // 登录账号
                            field.setAccessible(true);
                            field.set(parameter, sysUser.getUsername());
                            field.setAccessible(false);
                        }
                    }
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (SqlCommandType.DELETE == sqlCommandType) {
            // 添加删除记录
            LogDel logDel = new LogDel();
            logDel.setSqlStr(sql);
            logDel.setCreateTime(DateUtils.getDate());
            logDel.setIsUsed(0);
            logDelService.save(logDel);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

    //update-begin--Author:scott  Date:20191213 for:关于使用Quzrtz 开启线程任务, #465
    private LoginUser getLoginUser() {
        LoginUser sysUser;
        try {
            sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
        } catch (Exception e) {
            //e.printStackTrace();
            sysUser = null;
        }
        return sysUser;
    }
    //update-end--Author:scott  Date:20191213 for:关于使用Quzrtz 开启线程任务, #465

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

拦截mybatis(mybatis-plus)SQL 的相关文章

随机推荐

  • QT信号槽传递参数技巧

    信号槽如何传递参数 或带参数的信号槽 利用Qt进行程序开发时 有时需要信号槽来完成参数传递 带参数的信号槽在使用时 有几点需要注意的地方 下面结合实例进行介绍 第一点 当信号与槽函数的参数数量相同时 它们参数类型要完全一致 信号 cpp v
  • 力扣-图解算法数据结构

    常见的数据结构可分为 线性数据结构 与 非线性数据结构 具体为 数组 链表 栈 队列 树 图 散列表 堆 数组 数组是将相同类型的元素存储于连续内存空间的数据结构 其长度不可变 如下图所示 构建此数组需要在初始化时给定长度 并对数组每个索引
  • unity3d math 常用的数学

    1 计算游戏中敌人被击退的方向 类似 Vector3 lhs Vector3 this parentChara MoveDirection this parentChara MoveSpeed Vector3 rhs component p
  • 二十四史全译本

    现在正在读战争与和平 觉得这里面写了好多的历史的东西 所以想到以前读过的历史书籍 于是想找本历史书籍来看看 后来发现了二十四史全译本 就是对古文的历史解释为白话文 这是官方承认的正史了 应该值得一睹 所以下定决心 看一看这些历史书籍 201
  • 精品课程:Node+TS+Koa+Vue 商城全栈(前后端)开发

    课程目录 Node TS Koa商城全栈开发远程课介绍视频 Symbol与作用域 解构赋值与扩展运算符 字符串 数字与对象扩展 迭代 函数扩展 箭头函数 集合 Set对象 let和const 变量的解构赋值 数据结构Set 数据结构Map
  • Python 爬虫批量爬取网页图片保存到本地

    其实和爬取普通数据本质一样 不过我们直接爬取数据会直接返回 爬取图片需要处理成二进制数据保存成图片格式 jpg png等 的数据文本 现在贴一个url https img ivsky com img tupian t 201008 05 b
  • Python version 2.7 required, which was not found in the registry

    转自 http www cnblogs com min0208 archive 2012 05 24 2515584 html 安装setuptools的时候 不能再注册表中识别出来python2 7 在网上找了方法 仅作笔记 供下次使用
  • openwrt源下载太慢,make太慢等问题的处理

    目录 前言 一 在github获取源码 二 使用gitee获取源码 1 注册gitee 2 注册github 3 将openwrt官方github的源码fock到自己的github中 4 将github的openwrt源码导入到gitee
  • 一文看完2018苹果秋季新品发布会,你想知道的问题这里都有答案!

    苹果2018秋季新品发布会结束了 此处发布会看完下来内心毫无波澜 并没有多少惊艳到人的地方 倒是处处看到了国产手机发布会的影子 话不多说 下文给大家汇总一下本次苹果新品发布会的重点 命名有国产手机的气息 和此前网传的名字有一些出入 本次发布
  • R语言笔记二(控制结构)

    Control Structures Control structures in R allow you to control the flow of execution of the program depending on runtim
  • 正则表达式—HTML中的匹配

    从HTML中文本中提取Email地址和http URL 是在做爬虫时候的经常用到的技术 虽然变成语言本身可以帮助我们找到他们 但是用正则表达式来匹配也是很有用和具有实际意义的方法 一 匹配HTML Tag HTML不是有特别严格编程要求的
  • ISE14.7使用教程(一个完整工程的建立)

    ISE14 7使用教程 一个完整工程的建立 博主提到 黑金xlinix FPGA 黑金动力社区 http www heijin org 如需转载 请注明出处http www cnblogs com kingst 黑金官网 Http www
  • Linux ❉ ntpdate命令详解

    一 介绍 ntpdate命令用于同步更新互联网时间 或者NTP服务器时间 NTP服务器 Network Time Protocol NTP 是用来使计算机时间同步化的一种协议 它可以使计算机对其服务器或时钟源 如石英钟 GPS等等 做同步化
  • Spring事务与分布式事务

    一 事务的具体定义 事务提供一种机制将一个活动涉及的所有操作纳入到一个不可分割的执行单元 组成事务的所有操作只有在所有操作均能正常执行的情况下方能提交 只要其中任一操作执行失败 出现异常 都将导致整个事务的回滚 简单地说 事务提供一种 要么
  • 修改Oracle连接数

    修改Oracle连接数问题描述 客户端连接数据库报错 ORA 12516 TNS 监听程序无法找到匹配协议栈的可用句柄 解决过程 1 查看当前会话数 processes和sessions值 发现session数和2个参数的值已经非常逼近 S
  • LLVM Language Reference Manual

    摘要 该文档是LLVM汇编语言的参考指南 LLVM是基于表示的静态单赋值 SSA 该表示提供类型安全 低层级操作 灵活性 及简洁表示所有高层级语言的能力 这是贯穿各方面LLVM编译策略的通用代码表示 简介 LLVM代码表示用于三个不同形式
  • 宝塔SSL踩坑:SSL证书域名验证无反应

    1 申请 2 验证域名 申请通过之后就会校验域名 这里有坑 一开始我在这里点击验证域名 一直提示等待验证 我还以为要等一会 结果等了半天也没反应 百度了一下说要第二天 结果我等到第二天也没成功 这里的验证是需要登录到宝塔官网处理的 这里是第
  • 动画云创始人胥克谦&课程格子创始人李天放分享创业经历

    原文地址 http student csdn net mcd topic 163587 955044 2014年10月18日在北京科技大学成功举办了CSDN高校俱乐部全国巡讲 现场参会学生有一百余人 此次巡讲邀请到了皮影客CEO胥克谦和课程
  • 使用Java代码生成六个不重复的随机数字。

    使用Java代码生成六个不重复的随机数字 import java util Random public class tt5 public static void main String args int arr getArray for i
  • 拦截mybatis(mybatis-plus)SQL

    import java lang reflect Field import java util Date import java util Properties import org apache ibatis binding Mapper