• Mybatis-plus 怎么使用拦截器拿到SQL,并解析


    1、自定义拦截器

    1. package com.tigeriot.mqtt.config.mybatis;
    2. import cn.hutool.json.JSONUtil;
    3. import com.tigeriot.mqtt.common.CacheDev;
    4. import com.tigeriot.mqtt.common.CacheMQ;
    5. import com.tigeriot.mqtt.entity.log.DevLog;
    6. import com.tigeriot.mqtt.service.DevLogService;
    7. import com.tigeriot.mqtt.util.JsonUtils;
    8. import com.tigeriot.mqtt.util.SQLParseUtils;
    9. import org.apache.ibatis.binding.MapperMethod;
    10. import org.apache.ibatis.executor.Executor;
    11. import org.apache.ibatis.mapping.BoundSql;
    12. import org.apache.ibatis.mapping.MappedStatement;
    13. import org.apache.ibatis.plugin.*;
    14. import org.apache.ibatis.session.Configuration;
    15. import org.apache.ibatis.session.defaults.DefaultSqlSession;
    16. import org.springframework.beans.BeansException;
    17. import org.springframework.beans.factory.annotation.Autowired;
    18. import org.springframework.context.ApplicationContext;
    19. import org.springframework.context.ApplicationContextAware;
    20. import org.springframework.stereotype.Component;
    21. import java.lang.reflect.Method;
    22. import java.lang.reflect.Parameter;
    23. import java.util.Arrays;
    24. import java.util.Date;
    25. import java.util.Map;
    26. import java.util.Properties;
    27. @Intercepts({
    28. @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
    29. })
    30. public class OperationLogInterceptor implements Interceptor{
    31. @Override
    32. public Object intercept(Invocation invocation) throws Throwable {
    33. MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    34. Object parameter = invocation.getArgs()[1];
    35. BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    36. //sql
    37. String sql = boundSql.getSql();
    38. //获取表名
    39. String tableName = SQLParseUtils.getTableName(sql);
    40. if (tableName==null){
    41. throw new Exception("表名解析失败");
    42. }
    43. //如果是日志,就放行,不用加日志
    44. if (tableName.equalsIgnoreCase("DevLog")){
    45. return invocation.proceed();
    46. }
    47. long start =System.currentTimeMillis();
    48. // 执行 SQL 操作
    49. Object result = invocation.proceed();
    50. long end =System.currentTimeMillis();
    51. //参数
    52. String param = JsonUtils.getJson(parameter);
    53. System.out.println("json: "+param);
    54. //判断sql类型
    55. String sqlType = SQLParseUtils.parseSQLType(sql);
    56. if (sqlType==null){
    57. throw new Exception("日志SQL解析失败");
    58. }
    59. sql= sql.replaceAll("\n", "");
    60. Date createTime =new Date();
    61. Long executeTime=end-start;
    62. DevLog devLog = new DevLog(null, tableName, sqlType, sql, param, executeTime, createTime);
    63. System.out.println("devLog:"+devLog);
    64. boolean offer = CacheMQ.logQueue.offer(devLog);
    65. if (offer){
    66. System.out.println("成功放入队列,异步执行日志存入数据库");
    67. }
    68. return result;
    69. }
    70. @Override
    71. public Object plugin(Object target) {
    72. return Plugin.wrap(target, this);
    73. }
    74. @Override
    75. public void setProperties(Properties properties) {
    76. // 可以在此处配置插件的属性
    77. }
    78. // @Override
    79. // public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    80. // OperationLogInterceptor.applicationContext=applicationContext;
    81. // OperationLogInterceptor.devLogService=applicationContext.getBean(DevLogService.class);
    82. //
    83. // }
    84. }

    2、mybatis-config.xml配置文件

    1. "1.0" encoding="UTF8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <plugins>
    7. <plugin interceptor="com.tigeriot.mqtt.config.mybatis.OperationLogInterceptor">
    8. plugin>
    9. plugins>
    10. configuration>

    3、springboot配置 这个 mybatis-config.xml

    1. mybatis-plus:
    2. configLocation: classpath:mybatis/mybatis-config.xml

    4、SQL工具类

    1. package com.tigeriot.mqtt.util;
    2. import cn.hutool.json.JSONUtil;
    3. import java.util.Map;
    4. import java.util.regex.Pattern;
    5. import java.util.regex.Matcher;
    6. public class SQLParseUtils {
    7. public static String parseSQLType(String sql){
    8. if (sql==null){
    9. return null;
    10. }
    11. String type = sql.split(" ")[0];
    12. if (type.equalsIgnoreCase("INSERT")){
    13. return "INSERT";
    14. } else if (type.equalsIgnoreCase("UPDATE")) {
    15. return "UPDATE";
    16. } else if (type.equalsIgnoreCase("DELETE")) {
    17. return "DELETE";
    18. }else {
    19. return null;
    20. }
    21. }
    22. public static String getTableName(String sql) {
    23. String tableName = null;
    24. // 正则表达式匹配 INSERT、UPDATE 和 DELETE 语句
    25. String regex = "(?i)(?:INSERT\\s+INTO|UPDATE|DELETE\\s+FROM)\\s+(\\w+)";
    26. Pattern pattern = Pattern.compile(regex);
    27. Matcher matcher = pattern.matcher(sql.trim());
    28. if (matcher.find()) {
    29. tableName = matcher.group(1);
    30. }
    31. return tableName;
    32. }
    33. public static String getParam(String json,String type) throws Exception {
    34. // try {
    35. // if (type.equalsIgnoreCase("INSERT")){
    36. //
    37. //
    38. //
    39. // } else if (type.equalsIgnoreCase("UPDATE")) {
    40. // Map bean = JSONUtil.parseObj(json).toBean(Map.class);
    41. // Map o = (Map) bean.get("ew");
    42. // Object o1 = o.get("sqlSet");
    43. // return JsonUtils.getJson(o1);
    44. //
    45. //
    46. // }else if (type.equalsIgnoreCase("DELETE")){
    47. // Map bean = JSONUtil.parseObj(json).toBean(Map.class);
    48. // Map o = (Map) bean.get("ew");
    49. // Object o1 = o.get("paramNameValuePairs");
    50. // return JsonUtils.getJson(o1);
    51. //
    52. //
    53. // }else {
    54. // throw new Exception("type不合法");
    55. // }
    56. // } catch (Exception e) {
    57. // System.out.println(e.getMessage());
    58. // return null;
    59. // }
    60. return null;
    61. }
    62. public static void main(String[] args) {
    63. String tableName = getTableName("INSERT INTO orders (customer_id, product_id, quantity) VALUES (789, 123, 5)");
    64. System.out.println(tableName);
    65. }
    66. }

  • 相关阅读:
    git企业级使用
    C语言实现各类排序算法
    【C语言】算法:二分查找
    73.矩阵置零
    QtCreator开发环境的安装和配置
    Ubuntu或Mac (M1) 上安装Pymol
    【毕业设计】时间序列天气预测系统 - LSTM
    CS201 USB TYPEC音频控制芯片|TYPEC拓展坞音频芯片|CS201参数特性
    【校招VIP】java专业课之分页、分段
    Rust 在前端都干了些啥
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/134258701