spring+mybatis+log4j 输出SQL

1、在mybatis-config.xml配置中添加setting配置参数,会打印SQL执行结果
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

2、在spring-mybatis配置文件中添加配置参数
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:xxx/xxx/xxx/xxx/*.xml"></property>
</bean>

备注: 之前通过log4j的配置文件方式来实现,没有成功!!!项目环境:ssm+shiro

第二种方式(通过拦截器的方式)
1、在sqlSessionFactory 配置参数中,添加参数配置:
<property name="plugins">
  <list>
    <bean class="xxx.MybatisInterceptor"></bean>
  </list>
</property>

2、mybatis sql拦截器类
package xxx;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

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;
import org.apache.log4j.Logger;

/**
 * @author Tim
 *
 * 2019年4月24日
 * 
 * mybatis sql 拦截器
 */
@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 MybatisInterceptor implements Interceptor {
    private static final Logger log = Logger.getLogger(MybatisInterceptor.class);
    @Override
    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 returnVal = invocation.proceed();
        //获取sql语句
        String sql = getSql(configuration, boundSql);  
        log.info("#####拦截器获取SQL#### "+sql);
     //统计SQL执行时间
    
Object target = invocation.getTarget();
     Object result = null;
     if (target instanceof Executor) {
       long start = System.currentTimeMillis();
            Method method = invocation.getMethod();
            /**执行方法*/
            result = invocation.proceed();
            long end = System.currentTimeMillis();
            logger.info("[" + method.getName() + "] 耗时 [" + (end - start) + "] ms");
        }
    return returnVal;
    }

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

    @Override
    public void setProperties(Properties arg0) {
    }
    
    /**
     * 获取SQL
     * @param configuration
     * @param boundSql
     * @return
     */
    private String getSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();  
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();  
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");  
        if (parameterObject == null || parameterMappings.size() == 0) {
            return sql;
        }  
        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));  
                }  
            }  
        }  
        return sql;
    }

    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) + "'";  
        } else {  
            if (obj != null) {  
                value = obj.toString();  
            } else {  
                value = "";  
            }  
        }  
        return value;  
    }  
}

 

 
 

  

posted @ 2019-04-16 17:15  秋水秋色  阅读(1405)  评论(0编辑  收藏  举报