Plugins
摘一段来自MyBatis官方文档的文字。
MyBatis允许你在某一点拦截已映射语句执行的调用。默认情况下,MyBatis允许使用插件来拦截方法调用:
Executor(update、query、flushStatements、commint、rollback、getTransaction、close、isClosed)
ParameterHandler(getParameterObject、setParameters)
ResultSetHandler(handleResultSets、handleOutputParameters)
StatementHandler(prepare、parameterize、batch、update、query)
这些类中方法的详情可以通过查看每个方法的签名来发现,而且它们的源代码存在于MyBatis发行包中。你应该理解你所覆盖方法的行为,假设你所做的要比监视调用要多。如果你尝试修改或覆盖一个给定的方法,你可能会打破MyBatis的核心。这是低层次的类和方法,要谨慎使用插件。
插件示例:打印每条SQL语句及其执行时间
以下通过代码来演示一下如何使用MyBatis的插件,要演示的场景是:打印每条真正执行的SQL语句及其执行的时间。这是一个非常有用的需求,MyBatis本身的日志可以记录SQL,但是有以下几个问题:
MyBatis日志打印出来的SQL日志,参数都被占位符”?”替换,无法知道真正执行的SQL语句中的参数是什么
MyBatis日志打印出来的SQL日志,有大量的换行符,通常一句SQL语句要通过十几行显示,阅读体验非常差
无法记录SQL执行时间,有SQL执行时间就可以精准定位到执行时间比较慢的SQL
写MyBatis插件非常简单,只需要实现Interceptor接口即可,我这里将我的Interceptor命名为SqlCostInterceptor:
1 /** 2 * Sql执行时间记录拦截器 3 */ 4 @Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), 5 @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}), 6 @Signature(type = StatementHandler.class, method = "batch", args = { Statement.class })}) 7 public class SqlCostInterceptor implements Interceptor { 8 9 @Override 10 public Object intercept(Invocation invocation) throws Throwable { 11 Object target = invocation.getTarget(); 12 13 long startTime = System.currentTimeMillis(); 14 StatementHandler statementHandler = (StatementHandler)target; 15 try { 16 return invocation.proceed(); 17 } finally { 18 long endTime = System.currentTimeMillis(); 19 long sqlCost = endTime - startTime; 20 21 BoundSql boundSql = statementHandler.getBoundSql(); 22 String sql = boundSql.getSql(); 23 Object parameterObject = boundSql.getParameterObject(); 24 List parameterMappingList = boundSql.getParameterMappings(); 25 26 // 格式化Sql语句,去除换行符,替换参数 27 sql = formatSql(sql, parameterObject, parameterMappingList); 28 29 System.out.println("SQL:[" + sql + "]执行耗时[" + sqlCost + "ms]"); 30 } 31 } 32 33 @Override 34 public Object plugin(Object target) { 35 return Plugin.wrap(target, this); 36 } 37 38 @Override 39 public void setProperties(Properties properties) { 40 41 } 42 43 @SuppressWarnings("unchecked") 44 private String formatSql(String sql, Object parameterObject, List parameterMappingList) { 45 // 输入sql字符串空判断 46 if (sql == null || sql.length() == 0) { 47 return ""; 48 } 49 50 // 美化sql 51 sql = beautifySql(sql); 52 53 // 不传参数的场景,直接把Sql美化一下返回出去 54 if (parameterObject == null || parameterMappingList == null || parameterMappingList.size() == 0) { 55 return sql; 56 } 57 58 // 定义一个没有替换过占位符的sql,用于出异常时返回 59 String sqlWithoutReplacePlaceholder = sql; 60 61 try { 62 if (parameterMappingList != null) { 63 Class> parameterObjectClass = parameterObject.getClass(); 64 65 // 如果参数是StrictMap且Value类型为Collection,获取key="list"的属性,这里主要是为了处理循环时传入List这种参数的占位符替换 66 // 例如select * from xxx where id in ... 67 if (isStrictMap(parameterObjectClass)) { 68 StrictMap> strictMap = (StrictMap>)parameterObject; 69 70 if (isList(strictMap.get("list").getClass())) { 71 sql = handleListParameter(sql, strictMap.get("list")); 72 } 73 } else if (isMap(parameterObjectClass)) { 74 // 如果参数是Map则直接强转,通过map.get(key)方法获取真正的属性值 75 // 这里主要是为了处理、、、
分析一下这段代码(这个是改良过的版本,主要是增加了对select * from xxx where id in
首先是注解@Intercepts与@Signature,这两个注解是必须的,因为Plugin的wrap方法会取这两个注解里面参数。@Intercepts中可以定义多个@Signature,一个@Signature表示符合如下条件的方法才会被拦截:
接口必须是type定义的类型
方法名必须和method一致
方法形参的Class类型必须和args定义Class类型顺序一致
接着的一个问题是:有四个接口可以拦截,为什么使用StatementHandler去拦截?根据名字来看ParameterHandler和ResultSetHandler,前者处理参数,后者处理结果是不可能使用的,剩下的就是Executor和StatementHandler了。拦截StatementHandler的原因是而不是用Executor的原因是:
Executor的update与query方法可能用到MyBatis的一二级缓存从而导致统计的并不是真正的SQL执行时间
StatementHandler的update与query方法无论如何都会统计到PreparedStatement的execute方法执行时间,尽管也有一定误差(误差主要来自会将处理结果的时间也算上),但是相差不大
接着讲一下setProperties方法,可以将一些配置属性配置在
接着讲一下plugin方法,这里是为目标接口生成代理,不需要也没必要自己去写生成代理的方法,MyBatis的Plugin类已经为我们提供了wrap方法(当然如果自己有自己的逻辑也可以在Plugin.wrap方法前后加入,但是最终一定要使用Plugin.wrap方法生成代理),看一下该方法的实现:
1 public static Object wrap(Object target, Interceptor interceptor) { 2 Map, Set> signatureMap = getSignatureMap(interceptor); 3 Class> type = target.getClass(); 4 Class>[] interfaces = getAllInterfaces(type, signatureMap); 5 if (interfaces.length > 0) { 6 return Proxy.newProxyInstance( 7 type.getClassLoader(), 8 interfaces, 9 new Plugin(target, interceptor, signatureMap));10 }11 return target;12 }
因为这里的target一定是一个接口,因此可以放心使用JDK本身提供的Proxy类,这里相当于就是如果该接口满足方法签名那么就为之生成一个代理。
最后就是intercept方法了,这里就是拦截器的核心代码了,方法的逻辑我就不解释了,可以自己看一下,唯一要注意的一点就是无论如何最终一定要返回invocation.proceed(),保证拦截器的层层调用。
xml文件配置即效果演示
写完了插件,只需要在config.xml文件中进行一次配置即可,非常简单:
12 3
这里每个
有了类和这段配置,就可以使用SqlCostInterceptor了,SqlCostInterceptor是通用的,但是每个人的CRUD是不同的,我打印一下我这里CRUD执行的结果:
1 SQL:[insert into mail(id, create_time, modify_time, web_id, mail, use_for) values(null, now(), now(), "1", "123@sina.com", "个人使用");]执行耗时[1ms]2 SQL:[insert into mail(id, create_time, modify_time, web_id, mail, use_for) values(null, now(), now(), "2", "123@qq.com", "企业使用");]执行耗时[1ms]3 SQL:[insert into mail(id, create_time, modify_time, web_id, mail, use_for) values(null, now(), now(), "3", "123@sohu.com", "注册账号使用");]执行耗时[0ms]
看到打印了完整的SQl语句以及SQL语句执行时间。
不过要说明一点,这个插件只是一个简单的Demo,我并没有完整测试过,应该是无法覆盖所有场景的,所以如果想用这段代码片段打印真正的SQL及其执行时间的朋友,还需要在这个基础上做修改,不过即使不改代码,这个插件起到美化SQL的作用,去除一些换行符还是没问题的。
至于MyBatis插件的实现原理,会在我【MyBatis源码分析】系列文章中详细解读,文章地址为【MyBatis源码分析】插件实现原理。
后记
MyBatis插件机制非常有用,用得好可以解决很多问题,不只是这里的打印SQL语句以及记录SQL语句执行时间,分页、分表都可以通过插件来实现。用好插件的关键是我开头就列举的,这里再列一次:
Executor(update、query、flushStatements、commint、rollback、getTransaction、close、isClosed)
ParameterHandler(getParameterObject、setParameters)
ResultSetHandler(handleResultSets、handleOutputParameters)
StatementHandler(prepare、parameterize、batch、update、query)
只有理解这四个接口及相关方法是干什么的,才能写出好的拦截器,开发出符合预期的功能。
The above is the detailed content of Use of MyBatis plug-in--Print SQL and execution time. For more information, please follow other related articles on the PHP Chinese website!
mybatis first level cache and second level cache
What are the jquery plug-ins?
What is the difference between ibatis and mybatis
How to configure database connection in mybatis
What is the working principle and process of mybatis
What are the differences between hibernate and mybatis
Introduction to the plug-ins required for vscode to run java
Reasons why css loading failed