mybatis获取sql代码

package com.icourt.alpha.log.interceptor;

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.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher; /**
* 用于记录mybatis中的sql中不包含officeId的sql
* Created by shiwen on 2017/9/12.
* <p>
*/ @Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class})})
public class MybatisSqlInterceptor implements Interceptor { private static final Logger logger = LoggerFactory.getLogger(MybatisSqlInterceptor.class);
private static final Logger sqlLogger = LoggerFactory.getLogger("mybatisSql"); private static String [] officeIdNames = new String[]{"OFFICE_ID","OFFICEID","PK_OFFICE_ID"}; @Override
public Object intercept(Invocation invocation) throws Throwable {
try {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; //0.sql参数获取
Object parameter = null;
if (invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
} //1.获取sqlId
String sqlId = mappedStatement.getId();
BoundSql boundSql = mappedStatement.getBoundSql(parameter); Configuration configuration = mappedStatement.getConfiguration(); //获取真实的sql语句
String sql = getSql(configuration, boundSql, sqlId, 0); //2.判断是否有officeId
if (hasOfficeId(sql,officeIdNames)) {
sqlLogger.warn("{}", sql);
} else {
sqlLogger.debug("{}", sql);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return invocation.proceed();
} /**
* 判断sql语句中是否包含officeId字段
*
* @param sql sql语句
* @return
*/
private boolean hasOfficeId(String sql,String[] officeIdNames) {
//office ID 的可能名称
if (sql == null || sql.trim().length() == 0) {
return false;
} String afterWhereStatement = sql.toUpperCase().substring(sql.indexOf("where")); for (String officeIdName : officeIdNames){
if(afterWhereStatement.indexOf(officeIdName) > 0){
return true;
}
} return false;
} @Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
} @Override
public void setProperties(Properties properties) { } private static String getSql(Configuration configuration, BoundSql boundSql,
String sqlId, long time) {
String sql = showSql(configuration, boundSql);
StringBuilder str = new StringBuilder(100);
str.append(sqlId);
str.append(":");
str.append(sql);
return str.toString();
} private static String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
} }
return value;
} private static String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (!parameterMappings.isEmpty() && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration
.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?",
Matcher.quoteReplacement(getParameterValue(parameterObject))); } else {
MetaObject metaObject = configuration
.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql
.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} else {
sql = sql.replaceFirst("\\?", "缺失");
}//打印出缺失,提醒该参数缺失并防止错位
}
}
}
return sql;
}
}

mybatis拦截器获取sql的更多相关文章

  1. Mybatis拦截器实现SQL性能监控

    Mybatis拦截器只能拦截四类对象,分别为:Executor.ParameterHandler.StatementHandler.ResultSetHandler,而SQL数据库的操作都是从Exec ...

  2. Mybatis拦截器介绍

    拦截器的一个作用就是我们可以拦截某些方法的调用,我们可以选择在这些被拦截的方法执行前后加上某些逻辑,也可以在执行这些被拦截的方法时执行自己的逻辑而不再执行被拦截的方法.Mybatis拦截器设计的一个初 ...

  3. Mybatis拦截器实现分页

    本文介绍使用Mybatis拦截器,实现分页:并且在dao层,直接返回自定义的分页对象. 最终dao层结果: public interface ModelMapper { Page<Model&g ...

  4. 数据权限管理中心 - 基于mybatis拦截器实现

    数据权限管理中心 由于公司大部分项目都是使用mybatis,也是使用mybatis的拦截器进行分页处理,所以技术上也直接选择从拦截器入手 需求场景 第一种场景:行级数据处理 原sql: select ...

  5. 基于Spring和Mybatis拦截器实现数据库操作读写分离

    首先需要配置好数据库的主从同步: 上一篇文章中有写到:https://www.cnblogs.com/xuyiqing/p/10647133.html 为什么要进行读写分离呢? 通常的Web应用大多数 ...

  6. 通过spring抽象路由数据源+MyBatis拦截器实现数据库自动读写分离

    前言 之前使用的读写分离的方案是在mybatis中配置两个数据源,然后生成两个不同的SqlSessionTemplate然后手动去识别执行sql语句是操作主库还是从库.如下图所示: 好处是,你可以人为 ...

  7. spring boot 实现mybatis拦截器

    spring boot 实现mybatis拦截器 项目是个报表系统,服务端是简单的Java web架构,直接在请求参数里面加了个query id参数,就是mybatis mapper的query id ...

  8. mybatis拦截器使用

    目录 mybatis 拦截器接口Interceptor spring boot + mybatis整合 创建自己的拦截器MyInterceptor @Intercepts注解 mybatis拦截器入门 ...

  9. Mybatis拦截器介绍及分页插件

    1.1    目录 1.1 目录 1.2 前言 1.3 Interceptor接口 1.4 注册拦截器 1.5 Mybatis可拦截的方法 1.6 利用拦截器进行分页 1.2     前言 拦截器的一 ...

随机推荐

  1. UVALive5966(bfs)

    题意:给你一张n*m的图,其中: “ . ”代表可以走的空地 “ # ”代表不能走的墙 “ * ”代表传送门,当你从一个非传送们走到一个传送门的时候,你只能选择传送到除这个传送们外其他的传送门,如过没 ...

  2. Fibonacci Heaps

    Mergeable heapsA mergeable heap is any data structure that supports the following five operations,in ...

  3. ubuntu 升级 python3.5到 python3.6

    首先是在Ubuntu中安装python3.6 sudo apt-get install software-properties-common sudo add-apt-repository ppa:j ...

  4. Python pip源更改

    将pip源设置为阿里源 windows 打开文件资源管理器(文件夹地址中) 地址栏上面输入 %appdata% 在这里面新建一个文件夹pip 在pip文件夹里面新建一个文件叫做 pip.ini,内容如 ...

  5. terminal、Shell、tty和console

    最早的电脑有带很多开关和指示灯的面板——console(概念来自管风琴),一台电脑通常一个Console,化为主机一部分,和CPU共享机柜. 一台大型主机往往支持多用户,每个用户使用的终端——term ...

  6. SQL-触发器-011

    什么事触发器? 触发器是一种特殊的存储过程,当表中的数据发生改变时触发器自动生效: 触发器无法通过名称调用,也不允许设置参数. 触发器的类型: DML触发器(数据操作语言触发器-insert/upda ...

  7. iso系统镜像刻录到光盘和U盘

    使用UltraISO刻录 刻录U盘,点击文件,打开,选择镜像 启动,写入硬盘镜像选择U盘即可 刻录光盘 工具,刻录光盘映像,选择镜像,需要先插入光盘刻录机(有些电脑可能自带光驱盘,且有刻录功能,那么我 ...

  8. java 从一个工程action 跳转到另外一个工程action

    实现功能:java 从一个工程action 跳转到另外一个工程action 在我们实际编程的过程中,大家一定遇到过这种情况,那就是在一个工程中,需要使用到另外一个工程的实体Bean和方法.那么遇到这种 ...

  9. 怎样使用PL/SQL在不安装oracle 客户端的情况下使用oracle数据库

    在网上查了好多这方面的例子,但是似乎说的都不准确,在咨询朋友后终于实现了本机不安装oracle 的情况下,在windows系统上实现连接服务器上的数据库,现在贴出来与大家共享. 首先,我们需要一个PL ...

  10. react的注意点

    1.import Form from '../pages/form/view' 与 import Form from '../pages/form/container'的区别: 前者只是引入view. ...