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;  
    }  
}

 

 
 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM