1、在項目的applicationContext-dao.xml 文件中增加一個plugins:sqlStatementInterceptor
<bean id="dao-sqlsessionFactory" class="org.mybatis.sPRing.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="configLocation" value="classpath:config/mybatis-config.xml" /> --> <property name="mapperLocations"> <list> <value>classpath:com/test/mapper/*.xml</value> <value>classpath:com/test/mapper/extend/*.xml</value> </list> </property> <property name="plugins"> <array> <bean id="sqlStatementInterceptor" class="com.test.SqlStatementInterceptor"/> </array> </property> </bean>2、編寫sqlStatementInterceptor的實現代碼
package com.test;import java.util.Properties;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.plugin.*;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 數據庫操作性能攔截器,記錄耗時 */@Intercepts(value = { @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, CacheKey.class, BoundSql.class }), @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })public class SqlStatementInterceptor implements Interceptor{ private static Logger logger = LoggerFactory.getLogger(SqlStatementInterceptor.class); private Properties properties; @Override public Object intercept(Invocation arg0) throws Throwable { MappedStatement mappedStatement = (MappedStatement) arg0.getArgs()[0]; String sqlId = mappedStatement.getId(); Object returnValue; long start = System.currentTimeMillis(); returnValue = arg0.proceed(); long end = System.currentTimeMillis(); long time = end - start; StringBuilder str = new StringBuilder(100); str.append(sqlId); str.append(": "); str.append("cost time "); str.append(time); str.append(" ms."); String sqlInfo = str.toString(); logger.debug(sqlInfo); return returnValue; } @Override public Object plugin(Object arg0) { return Plugin.wrap(arg0, this); } @Override public void setProperties(Properties arg0) { this.properties = arg0; }}3、對sqlStatementInterceptor.java類里面的輸出級別(上面代碼塊是debug級別),進行相應的logback.xml設置(只需修改文件內的level標簽)4、啟動項目,從log文件中可看到日志打印[http-8080-5] DEBUG [Caller+0 at com.test.SqlStatementInterceptor.intercept(SqlStatementInterceptor.java:49) ] - com.test.testMapper.selectByExample: cost time 1 ms.參考文章:
https://my.oschina.net/u/2265143/blog/786295
http://blog.csdn.net/tq02h2a/article/details/50772652
新聞熱點
疑難解答