Mybatis SQL拦截器实现

简介: 主要功能:通过log4j配置mybatis的打印,只能输出到控制台,而并非真正能够实现sql的获取,本文主要通过拦截器实现sql的拦截,进而对sql进行相应的操作。 起因:因项目需要,服务器要配成双机热备,那么数据库(这里采用的是MySQL)也是双机的,这就牵涉到数据库同步的问题,由于某种原因(这就不透露了)不能采用MySQL自身的同步机制,采用原先C/S系统的同步机制进行同步。

主要功能:通过log4j配置mybatis的打印,只能输出到控制台,而并非真正能够实现sql的获取,本文主要通过拦截器实现sql的拦截,进而对sql进行相应的操作。

起因:因项目需要,服务器要配成双机热备,那么数据库(这里采用的是MySQL)也是双机的,这就牵涉到数据库同步的问题,由于某种原因(这就不透露了)不能采用MySQL自身的同步机制,采用原先C/S系统的同步机制进行同步。

实现方式:mybatis与主数据库正常交互,通过拦截器拦截sql并通过webservice将sql发送到C/S系统的同步模块,进而同步备数据库。

主要代码:

package com.shr.dao;
 
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
 
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import javax.inject.Inject;
import javax.inject.Named;

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.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.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;
 
@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 Logger logger = Logger.getLogger(MyBatisSQLInterceptor.class.getSimpleName());
	
    @SuppressWarnings("unused")
	private Properties properties;
    
    private ConcurrentLinkedDeque<String> list = new ConcurrentLinkedDeque<String>();
//    @Inject
//    @Named("soapClient")
//    private SoapClient soapClient;
    
    public MyBatisSQLInterceptor()
    {
    	ExecutorService exec = Executors.newSingleThreadExecutor();
    	exec.execute(new Thread(){
    		public void run(){
    			while(true)
    			{
    				if(list.isEmpty() == false)
    				{
    					String sql = list.pollFirst();
    					logger.info("[SEND WS: ["+sql+"]]");
    					//与WebService交互
    				}
    				try {
						TimeUnit.MILLISECONDS.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    		}
    	});
    	
    	exec.shutdown();
    }
 
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Object returnValue = null;
        returnValue = invocation.proceed();
        showSql(configuration, boundSql);
        return returnValue;
    }
 
    private 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(obj) + "'";
//            System.out.println(value);
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
 
        }
        return value;
    }
 
    public String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", 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("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        logger.info(sql);
        if(sql.startsWith("select") == false)
        {
        	list.add(sql);
        }
        return sql;
    }
 
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
 
    public void setProperties(Properties properties0) {
        this.properties = properties0;
    }
}


目录
相关文章
|
15天前
|
SQL XML Java
mybatis 调用修改SQL时 出现了一个问题 没有修改成功也没有报错
mybatis 调用修改SQL时 出现了一个问题 没有修改成功也没有报错
18 0
|
1月前
|
SQL XML Java
程序员都要懂的SQL防注入Mybatis框架SQL防注入
程序员都要懂的SQL防注入Mybatis框架SQL防注入
22 0
|
1天前
|
SQL Java 数据库连接
【mybatis】动态sql之批量增删改查
【mybatis】动态sql之批量增删改查
5 0
|
1天前
|
SQL 监控 Java
mybatis拦截器实现
mybatis拦截器实现
5 0
|
11天前
|
SQL 安全 Java
【Mybatis】Mybatis如何防止sql注入
【Mybatis】Mybatis如何防止sql注入
|
12天前
|
SQL Java 数据库连接
【Mybatis】动态sql之sql的复用
【Mybatis】动态sql之sql的复用
10 0
|
14天前
|
SQL Java 关系型数据库
mybatis-plus启动时自动执行sql脚本
mybatis-plus启动时自动执行sql脚本
19 1
|
16天前
|
SQL Java 数据库连接
Javaweb之Mybatis的动态SQL的详细解析
Javaweb之Mybatis的动态SQL的详细解析
11 0
|
6月前
|
SQL 安全 Java
MyBatis映射文件深入--动态sql
MyBatis映射文件深入--动态sql
47 0
|
6月前
|
SQL XML Java
mybatis的注解开发之三种动态sql
mybatis的注解开发之三种动态sql