经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
Springboot自定义mybatis拦截器实现扩展
来源:jb51  时间:2021/12/31 17:27:03  对本文有异议

前言

相信大家对拦截器并不陌生,对mybatis也不陌生。

有用过pagehelper的,那么对mybatis拦截器也不陌生了,按照使用的规则触发sql拦截,帮我们自动添加分页参数 。

那么今天,我们的实践 自定义mybatis拦截器也是如此, 本篇文章实践的效果:

针对一些使用 单个实体类去接收返回结果的 mapper方法,我们拦截检测,如果没写 LIMIT 1 ,我们将自动帮忙填充,达到查找单条数据 效率优化的效果。

ps: 当然,跟着该篇学会了这个之后,那么可以扩展的东西就多了,大家按照自己的想法或是项目需求都可以自己发挥。 我该篇的实践仅仅作为抛砖引玉吧。

正文

实践的准备 :

整合mybatis ,然后故意写了3个查询方法, 1个是list 列表数据,2个是 单条数据 。

我们通过自己写一个MybatisInterceptor实现 mybatis框架的 Interceptor来做文章:

MybatisInterceptor.java :

  1. import org.apache.ibatis.executor.Executor;
  2. import org.apache.ibatis.mapping.*;
  3. import org.apache.ibatis.plugin.*;
  4. import org.apache.ibatis.session.ResultHandler;
  5. import org.apache.ibatis.session.RowBounds;
  6. import org.springframework.stereotype.Component;
  7. import java.lang.reflect.Method;
  8. import java.util.*;
  9. /**
  10. * @Author JCccc
  11. * @Description
  12. * @Date 2021/12/14 16:56
  13. */
  14. @Component
  15. @Intercepts({
  16. @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
  17. @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
  18. })
  19. public class MybatisInterceptor implements Interceptor {
  20. @Override
  21. public Object intercept(Invocation invocation) throws Throwable {
  22. //获取执行参数
  23. Object[] objects = invocation.getArgs();
  24. MappedStatement ms = (MappedStatement) objects[0];
  25. //解析执行sql的map方法,开始自定义规则匹配逻辑
  26. String mapperMethodAllName = ms.getId();
  27. int lastIndex = mapperMethodAllName.lastIndexOf(".");
  28. String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
  29. String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));
  30. Class<?> mapperClass = Class.forName(mapperClassStr);
  31. Method[] methods = mapperClass.getMethods();
  32. Class<?> returnType;
  33. for (Method method : methods) {
  34. if (method.getName().equals(mapperClassMethodStr)) {
  35. returnType = method.getReturnType();
  36. if (returnType.isAssignableFrom(List.class)) {
  37. System.out.println("返回类型是 List");
  38. System.out.println("针对List 做一些操作");
  39. } else if (returnType.isAssignableFrom(Set.class)) {
  40. System.out.println("返回类型是 Set");
  41. System.out.println("针对Set 做一些操作");
  42. } else{
  43. BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
  44. String oldSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
  45. if (!oldSql.contains("LIMIT")){
  46. String newSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ") + " LIMIT 1";
  47. BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
  48. boundSql.getParameterMappings(), boundSql.getParameterObject());
  49. MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));
  50. for (ParameterMapping mapping : boundSql.getParameterMappings()) {
  51. String prop = mapping.getProperty();
  52. if (boundSql.hasAdditionalParameter(prop)) {
  53. newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
  54. }
  55. }
  56. Object[] queryArgs = invocation.getArgs();
  57. queryArgs[0] = newMs;
  58. System.out.println("打印新SQL语句" + newSql);
  59. }
  60. }
  61. }
  62. }
  63. //继续执行逻辑
  64. return invocation.proceed();
  65. }
  66. @Override
  67. public Object plugin(Object o) {
  68. //获取代理权
  69. if (o instanceof Executor) {
  70. //如果是Executor(执行增删改查操作),则拦截下来
  71. return Plugin.wrap(o, this);
  72. } else {
  73. return o;
  74. }
  75. }
  76. /**
  77. * 定义一个内部辅助类,作用是包装 SQL
  78. */
  79. class MyBoundSqlSqlSource implements SqlSource {
  80. private BoundSql boundSql;
  81. public MyBoundSqlSqlSource(BoundSql boundSql) {
  82. this.boundSql = boundSql;
  83. }
  84. @Override
  85. public BoundSql getBoundSql(Object parameterObject) {
  86. return boundSql;
  87. }
  88. }
  89. private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
  90. MappedStatement.Builder builder = new
  91. MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
  92. builder.resource(ms.getResource());
  93. builder.fetchSize(ms.getFetchSize());
  94. builder.statementType(ms.getStatementType());
  95. builder.keyGenerator(ms.getKeyGenerator());
  96. if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
  97. builder.keyProperty(ms.getKeyProperties()[0]);
  98. }
  99. builder.timeout(ms.getTimeout());
  100. builder.parameterMap(ms.getParameterMap());
  101. builder.resultMaps(ms.getResultMaps());
  102. builder.resultSetType(ms.getResultSetType());
  103. builder.cache(ms.getCache());
  104. builder.flushCacheRequired(ms.isFlushCacheRequired());
  105. builder.useCache(ms.isUseCache());
  106. return builder.build();
  107. }
  108. @Override
  109. public void setProperties(Properties properties) {
  110. //读取mybatis配置文件中属性
  111. }
  112. }

简单代码端解析:

① 拿出执行参数,里面有很多东西给我们用的,我本篇主要是用MappedStatement。大家可以发挥自己的想法。 打debug可以自己看看里面的东西。

  1. //获取执行参数
  2. Object[] objects = invocation.getArgs();
  3. MappedStatement ms = (MappedStatement) objects[0];

 

 ② 这里我主要是使用了从MappedStatement里面拿出来的id,做切割分别切出来 目前执行的sql的mapper是哪个,然后方法是哪个。

  1. String mapperMethodAllName = ms.getId();
  2. int lastIndex = mapperMethodAllName.lastIndexOf(".");
  3. String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
  4. String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));

③ 这就是我自己随便写的一下,我直接根据切割出来的mapper类找出里面的方法,主要是为了拿出每个方法的返回类型,因为 我这篇实践内容就是,判断出单个pojo接受的mapper方法,加个LIMIT 1 , 其他的 LIST 、SET 、 Page 等等这些,我暂时不做扩展。

  1. Class<?> mapperClass = Class.forName(mapperClassStr);
  2. Method[] methods = mapperClass.getMethods();
  3. Class<?> returnType;

 ④这一段代码就是该篇的拓展逻辑了,从MappedStatement里面拿出 SqlSource,然后再拿出BoundSql,然后一顿操作 给加上 LIMIT 1  , 然后new 一个新的 MappedStatement,一顿操作塞回去invocation 里面

  1. BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
  2. String oldSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
  3. if (!oldSql.contains("LIMIT")){
  4. String newSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ") + " LIMIT 1";
  5. BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
  6. boundSql.getParameterMappings(), boundSql.getParameterObject());
  7. MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));
  8. for (ParameterMapping mapping : boundSql.getParameterMappings()) {
  9. String prop = mapping.getProperty();
  10. if (boundSql.hasAdditionalParameter(prop)) {
  11. newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
  12. }
  13. }
  14. Object[] queryArgs = invocation.getArgs();
  15. queryArgs[0] = newMs;
  16. System.out.println("打印新SQL语句:" + newSql);
  17. }

OK,最后简单来试试效果 :
 

 

最后再重申一下,本篇文章内容只是一个抛砖引玉,随便想的一些实践效果,大家可以按照自己的想法发挥。

最后再补充一个 解决 mybatis自定义拦截器和 pagehelper 拦截器 冲突导致失效的问题出现的

解决方案:

加上一个拦截器配置类 

MyDataSourceInterceptorConfig.java :

  1. import org.apache.ibatis.session.SqlSessionFactory;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.ApplicationListener;
  4. import org.springframework.context.event.ContextRefreshedEvent;
  5. import org.springframework.stereotype.Component;
  6. import java.util.List;
  7. /**
  8. * @Author JCccc
  9. * @Description
  10. * @Date 2021/12/14 16:56
  11. */
  12. @Component
  13. public class MyDataSourceInterceptorConfig implements ApplicationListener<ContextRefreshedEvent> {
  14. @Autowired
  15. private MybatisInterceptor mybatisInterceptor;
  16. @Autowired
  17. private List<SqlSessionFactory> sqlSessionFactories;
  18. @Override
  19. public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
  20. for (SqlSessionFactory factory : sqlSessionFactories) {
  21. factory.getConfiguration().addInterceptor(mybatisInterceptor);
  22. }
  23. }
  24. }

最后最后再补充多一些,

文中 针对拦截的是Executor 这种接口的插件,

其实 还可以使用ParameterHandler、ResultSetHandler、StatementHandler。

每当执行这四种接口对象的方法时,就会进入拦截方法,然后我们可以根据不同的插件去拿不同的参数。

类似:

  1. @Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class,Integer.class})

然后可以做个转换,也是可以取出相关的 BoundSql 等等 :

  1. if (!(invocation.getTarget() instanceof RoutingStatementHandler)){
  2. return invocation.proceed();
  3. }
  4. RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
  5. BoundSql boundSql = statementHandler.getBoundSql();
  6. String sql = boundSql.getSql().toUpperCase();

ParameterHandler、ResultSetHandler、StatementHandler、Executor ,不同的插件拦截,有不同的使用场景,想深入的看客们,可以深一下。

到此这篇关于Springboot自定义mybatis拦截器实现扩展的文章就介绍到这了,更多相关Springboot mybatis拦截器内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号