关键词搜索

源码搜索 ×
×

Mybatis SQL拦截器实现

发布2015-08-27浏览9431次

详情内容

欢迎支持笔者新作:《深入理解Kafka:核心设计与实践原理》和《RabbitMQ实战指南》,同时欢迎关注笔者的微信公众号:朱小厮的博客。

 

欢迎跳转到本文原文阅读:https://honeypps.com/java/mybatis-sql-interceptor/

 

主要功能:通过log4j配置mybatis的打印,只能输出到控制台,而并非真正能够实现sql的获取,本文主要通过拦截器实现sql的拦截,进而对sql进行相应的操作。

起因:因项目需要,服务器要配成双机热备,那么数据库(这里采用的是MySQL)也是双机的,这就牵涉到数据库同步的问题,由于某种原因(这就不透露了)不能采用MySQL自身的同步机制,采用原先C/S系统的同步机制进行同步。

实现方式:mybatis与主数据库正常交互,通过拦截器拦截sql并通过webservice将sql发送到C/S系统的同步模块,进而同步备数据库。

主要代码:

 

  1. package com.shr.dao;
  2. import java.text.DateFormat;
  3. import java.util.Date;
  4. import java.util.List;
  5. import java.util.Locale;
  6. import java.util.Properties;
  7. import java.util.concurrent.ConcurrentLinkedDeque;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.TimeUnit;
  11. import org.apache.log4j.Logger;
  12. import javax.inject.Inject;
  13. import javax.inject.Named;
  14. import org.apache.ibatis.executor.Executor;
  15. import org.apache.ibatis.mapping.BoundSql;
  16. import org.apache.ibatis.mapping.MappedStatement;
  17. import org.apache.ibatis.mapping.ParameterMapping;
  18. import org.apache.ibatis.plugin.Interceptor;
  19. import org.apache.ibatis.plugin.Intercepts;
  20. import org.apache.ibatis.plugin.Invocation;
  21. import org.apache.ibatis.plugin.Plugin;
  22. import org.apache.ibatis.plugin.Signature;
  23. import org.apache.ibatis.reflection.MetaObject;
  24. import org.apache.ibatis.session.Configuration;
  25. import org.apache.ibatis.session.ResultHandler;
  26. import org.apache.ibatis.session.RowBounds;
  27. import org.apache.ibatis.type.TypeHandlerRegistry;
  28. @Intercepts({
  29. @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
  30. @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
  31. RowBounds.class, ResultHandler.class }) })
  32. public class MyBatisSQLInterceptor implements Interceptor {
  33. private Logger logger = Logger.getLogger(MyBatisSQLInterceptor.class.getSimpleName());
  34. @SuppressWarnings("unused")
  35. private Properties properties;
  36. private ConcurrentLinkedDeque<String> list = new ConcurrentLinkedDeque<String>();
  37. // @Inject
  38. // @Named("soapClient")
  39. // private SoapClient soapClient;
  40. public MyBatisSQLInterceptor()
  41. {
  42. ExecutorService exec = Executors.newSingleThreadExecutor();
  43. exec.execute(new Thread(){
  44. public void run(){
  45. while(true)
  46. {
  47. if(list.isEmpty() == false)
  48. {
  49. String sql = list.pollFirst();
  50. logger.info("[SEND WS: ["+sql+"]]");
  51. //与WebService交互
  52. }
  53. try {
  54. TimeUnit.MILLISECONDS.sleep(100);
  55. } catch (InterruptedException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. });
  61. exec.shutdown();
  62. }
  63. public Object intercept(Invocation invocation) throws Throwable {
  64. MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
  65. Object parameter = null;
  66. if (invocation.getArgs().length > 1) {
  67. parameter = invocation.getArgs()[1];
  68. }
  69. BoundSql boundSql = mappedStatement.getBoundSql(parameter);
  70. Configuration configuration = mappedStatement.getConfiguration();
  71. Object returnValue = null;
  72. returnValue = invocation.proceed();
  73. showSql(configuration, boundSql);
  74. return returnValue;
  75. }
  76. private String getParameterValue(Object obj) {
  77. String value = null;
  78. if (obj instanceof String) {
  79. value = "'" + obj.toString() + "'";
  80. } else if (obj instanceof Date) {
  81. DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
  82. value = "'" + formatter.format(obj) + "'";
  83. // System.out.println(value);
  84. } else {
  85. if (obj != null) {
  86. value = obj.toString();
  87. } else {
  88. value = "";
  89. }
  90. }
  91. return value;
  92. }
  93. public String showSql(Configuration configuration, BoundSql boundSql) {
  94. Object parameterObject = boundSql.getParameterObject();
  95. List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  96. String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
  97. if (parameterMappings.size() > 0 && parameterObject != null) {
  98. TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  99. if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
  100. sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
  101. } else {
  102. MetaObject metaObject = configuration.newMetaObject(parameterObject);
  103. for (ParameterMapping parameterMapping : parameterMappings) {
  104. String propertyName = parameterMapping.getProperty();
  105. if (metaObject.hasGetter(propertyName)) {
  106. Object obj = metaObject.getValue(propertyName);
  107. sql = sql.replaceFirst("\\?", getParameterValue(obj));
  108. } else if (boundSql.hasAdditionalParameter(propertyName)) {
  109. Object obj = boundSql.getAdditionalParameter(propertyName);
  110. sql = sql.replaceFirst("\\?", getParameterValue(obj));
  111. }
  112. }
  113. }
  114. }
  115. logger.info(sql);
  116. if(sql.startsWith("select") == false)
  117. {
  118. list.add(sql);
  119. }
  120. return sql;
  121. }
  122. public Object plugin(Object target) {
  123. return Plugin.wrap(target, this);
  124. }
  125. public void setProperties(Properties properties0) {
  126. this.properties = properties0;
  127. }
  128. }

 

 

欢迎支持笔者新作:《深入理解Kafka:核心设计与实践原理》和《RabbitMQ实战指南》,同时欢迎关注笔者的微信公众号:朱小厮的博客。

 

欢迎跳转到本文原文阅读:https://honeypps.com/java/mybatis-sql-interceptor/

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载