SpringMVC打印完整SQL并记录SQL耗时
⾸先需要写⼀个数据库操作性能:
import java.util.Date;
import java.util.List;
import java.util.Properties;
import Matcher;
import org.apache.ibatis.cache.CacheKey;
import org.utor.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.flection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.pe.TypeHandlerRegistry;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
/**
* 数据库操作性能,记录耗时
*/
@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 = Logger(SqlStatementInterceptor.class);
private Properties properties;
@Override
public Object intercept(Invocation invocation) throws Throwable
{
Object returnValue;
long start = System.currentTimeMillis();
returnValue = invocation.proceed();
long end = System.currentTimeMillis();
long time = end - start;
try {
final Object[] args = Args();
//获取原始的ms
MappedStatement ms = (MappedStatement) args[0];
Object parameter = null;
//获取参数,if语句成⽴,表⽰sql语句有参数,参数格式是map形式
if (Args().length > 1) {
parameter = Args()[1];
}
String sqlId = ms.getId();// 获取到节点的id,即sql语句的id
BoundSql boundSql = ms.getBoundSql(parameter); // BoundSql就是封装myBatis最终产⽣的sql类
Configuration configuration = ms.getConfiguration(); // 获取节点的配置
String sql = getSql(configuration, boundSql, sqlId,time); // 获取到最终的sql语句
<(sql);
logger.warn(sql);
System.out.println(sql);
} catch (Exception e) {
<("拦截sql处理出差"+e.getMessage());
e.printStackTrace();
}
return returnValue;
}
// 封装了⼀下sql语句,使得结果返回完整xml路径下的sql语句节点id + sql语句
public static String getSql(Configuration configuration, BoundSql boundSql,String sqlId,long time) {
String sql = showSql(configuration, boundSql);
StringBuilder str = new StringBuilder(100);
str.append("\n\n============================begin【zndoc】================================\n\n");
str.append(sqlId);
str.append(":耗时【");
str.append(time);
str.append("】毫秒\n\n");
str.append(sql);
str.append("\n\n============================end【zndoc】================================\n\n");
String();
}
/*<br> *如果参数是String,则添加单引号,如果是⽇期,则转换为时间格式器并加单引号;对参数是null和不是null的情况作了处理<br> */
private static String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + String() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = String();
} else {
value = "";
}
}
return value;
}
// 进⾏?的替换
public static String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = ParameterObject(); // 获取参数
List<ParameterMapping> parameterMappings = boundSql
.getParameterMappings();
String sql = Sql().replaceAll("[\\s]+", ""); // sql语句中多个空格都⽤⼀个空格代替
if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) {
mybatis和springmvcTypeHandlerRegistry typeHandlerRegistry = TypeHandlerRegistry(); // 获取类型处理器注册器,类型处理器的功能是进⾏java类型和数据库类型的转换<br> // 如果根据Class()可以到对if (typeHandlerRegistry.Class())) {
sql = placeFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
} else {
MetaObject metaObject = wMetaObject(parameterObject);// MetaObject主要是封装了
originalObject对象,提供了get和set的⽅法⽤于获取和设置originalObject的属性值,主要⽀持对JavaBean、Collection、Map三种类型对for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = Property();
if (metaObject.hasGetter(propertyName)) {
Object obj = Value(propertyName);
sql = placeFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = AdditionalParameter(propertyName); // 该分⽀是动态sql
sql = placeFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
}else{placeFirst("\\?","缺失");}//打印出缺失,提醒该参数缺失并防⽌错位
}
}
}
return sql;
}
@Override
public Object plugin(Object arg0)
{
return Plugin.wrap(arg0, this);
}
@Override
public void setProperties(Properties arg0)
{
this.properties = arg0;
}
}
然后在l⾥⾯配置,sessionFactory的bean⾥⾯添加:
<property name="plugins">
<array>
<bean id="sqlStatementInterceptor"class="com.vk.updoc.security.SqlStatementInterceptor" /> </array>
</property>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论