当前位置: 首页 > news >正文

Mybatis插件入门

专栏精选

引入Mybatis

Mybatis的快速入门

Mybatis的增删改查扩展功能说明

mapper映射的参数和结果

Mybatis复杂类型的结果映射

Mybatis基于注解的结果映射

Mybatis枚举类型处理和类型处理器

再谈动态SQL

Mybatis配置入门

Mybatis行为配置之Ⅰ—缓存

Mybatis行为配置之Ⅱ—结果相关配置项说明

Mybatis行为配置之Ⅲ—其他行为配置项说明

Mybatis行为配置之Ⅳ—日志

Mybatis整合Spring详解

Mybatis插件入门

Mybatis专栏代码资源

文章目录

  • 专栏精选
  • 引言
  • 摘要
  • 正文
    • SQL耗时插件
    • 分页插件
  • 总结

引言

大家好,我是奇迹老李,一个专注于分享开发经验和基础教程的博主。欢迎来到我的频道,这里汇聚了汇集编程技巧、代码示例和技术教程,欢迎广大朋友们点赞评论提出意见,重要的是点击关注喔 🙆,期待在这里与你共同度过美好的时光🕹️。今天要和大家分享的内容是Mybatis插件。做好准备,Let’s go🚎🚀

摘要

在这篇文章中,我们将简单介绍Mybatis的插件开发,了解插件的基本使用方法,我将以计算sql耗时、分页查询两个简单的插件为例带领大家领略Mybatis插件的魅力。准备好开启今天的神奇之旅了吗?

正文

首图

Mybatis中也提供了插件的功能,虽然叫插件,但是实际上是通过拦截器(Interceptor)实现的。在MyBatis的插件模块中涉及责任链模式和JDK动态代理
–《Mybatis技术内幕(徐郡明 编著)》

在mybatis项目中通过实现 org.apache.ibatis.plugin.Interceptor接口可以定义一个拦截器,重写 intercept()方法来定义拦截器的具体操作。同时通过 @org.apache.ibatis.plugin.Intercepts@org.apache.ibatis.plugin.Signature注解定义需要被拦截的位置(类和方法)。常见的插件如分库分表、自动分页、数据脱敏、加密解密等等

下面以两个简单的例子,说明拦截器的具体实现

SQL耗时插件

@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
public class SqlCostTimeInterceptor implements Interceptor {private static Logger logger = LoggerFactory.getLogger(SqlCostTimeInterceptor.class);@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object target = invocation.getTarget();long startTime = System.currentTimeMillis();StatementHandler statementHandler = (StatementHandler) target;try {return invocation.proceed();} finally {long costTime = System.currentTimeMillis() - startTime;BoundSql boundSql = statementHandler.getBoundSql();String sql = boundSql.getSql();logger.info("执行 SQL:[ {} ]执行耗时[ {} ms]", sql, costTime);}}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {System.out.println("插件配置的信息:"+properties);}
}
<!-- MyBatis全局配置文件:mybatis-config.xml -->
<plugins><plugin interceptor="com.xzg.cd.a88.SqlCostTimeInterceptor"><property name="someProperty" value="100"/></plugin>
</plugins>

分页插件

mybatis分页的详细实现思路可参考 MyBatis分页插件PageHelper项目

实现思路如下:

  1. 拦截 org.apache.ibatis.executor.Executor#query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler)方法
  2. 获取到rowBounds参数中的offsetlimit
  3. 获取到 MappedStatement参数中的sql语句,并根据上一步中的分页参数重新构建分页sql
  4. 使用上一步生成的分页sql语句构建新的MappedStatement,替换原有 MappedStatement
  5. 执行查询操作

代码如下

package top.sunyog.mybatis.plugins;  import org.apache.ibatis.executor.Executor;  
import org.apache.ibatis.mapping.BoundSql;  
import org.apache.ibatis.mapping.MappedStatement;  
import org.apache.ibatis.mapping.SqlSource;  
import org.apache.ibatis.plugin.Interceptor;  
import org.apache.ibatis.plugin.Intercepts;  
import org.apache.ibatis.plugin.Invocation;  
import org.apache.ibatis.plugin.Signature;  
import org.apache.ibatis.session.Configuration;  
import org.apache.ibatis.session.ResultHandler;  
import org.apache.ibatis.session.RowBounds;  import java.util.Properties;  @Intercepts({@Signature(type = Executor.class, method = "query"  , args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})  
public class PageHelperInterceptor implements Interceptor {  private final int STATEMENT_ARG_INDEX = 0;  private final int PARAMETER_ARG_INDEX = 1;  private final int ROWBOUND_ARG_INDEX = 2;  @Override  public Object intercept(Invocation invocation) throws Throwable {  Object[] args = invocation.getArgs();  //获取待查sql  MappedStatement ms = (MappedStatement) args[STATEMENT_ARG_INDEX];  Object parameter = args[PARAMETER_ARG_INDEX];  BoundSql sql = ms.getBoundSql(parameter);  String sqlStr = sql.getSql().trim();  //获取分页内容  RowBounds rowBounds = (RowBounds) args[ROWBOUND_ARG_INDEX];  int limit = rowBounds.getLimit();  int offset = rowBounds.getOffset();  //重新拼接sql  StringBuffer buffer = new StringBuffer(sqlStr.length() + 100);  buffer.append("select t.* from (");  buffer.append(sqlStr);  buffer.append(") t limit ").append(offset).append(", ").append(limit);  //创建新的statement  Configuration config = ms.getConfiguration();  BoundSql newBoundSql = new BoundSql(config, buffer.toString(), sql.getParameterMappings(), parameter);  SqlSource sqlSource = o -> newBoundSql;  //按照原有ms生成新ms  MappedStatement.Builder builder = new MappedStatement.Builder(config, ms.getId(), sqlSource, ms.getSqlCommandType());  builder.resource(ms.getResource())  .fetchSize(ms.getFetchSize())  .statementType(ms.getStatementType())  .keyGenerator(ms.getKeyGenerator())  .timeout(ms.getTimeout())  .parameterMap(ms.getParameterMap())  .resultMaps(ms.getResultMaps())  .resultSetType(ms.getResultSetType())  .cache(ms.getCache())  .flushCacheRequired(ms.isFlushCacheRequired())  .useCache(ms.isUseCache());  //替换原来的ms  args[STATEMENT_ARG_INDEX] = builder.build();  //替换原来的rowBound  RowBounds newRowBounds = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);  args[ROWBOUND_ARG_INDEX] = newRowBounds;  return invocation.proceed();  }  @Override  public Object plugin(Object target) {  return Interceptor.super.plugin(target);  }  @Override  public void setProperties(Properties properties) {  Interceptor.super.setProperties(properties);  }  
}

配置文件中添加插件配置,注意mybatis配置文件中标签的顺序

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "https://mybatis.org/dtd/mybatis-3-config.dtd">  
<configuration>  <properties resource="mysql-env.properties">  <property name="test-key" value="test-value-c"/>  </properties>  <settings>...</settings><typeAliases>...</typeAliases>  <typeHandlers>...</typeHandlers><plugins>  <plugin interceptor="top.sunyog.mybatis.plugins.PageHelperInterceptor"/>  </plugins><environments>...</environments><mappers>...</mappers>
</configuration>

测试代码如下:

private void testListPage(){  SqlSession sqlSession = MybatisAppContext.getSqlSessionFactory().openSession();  final String statement="top.sunyog.mybatis.mapper.LessonMapper.getDemos";  //调用被拦截的方法sqlSession.select(statement, null, new RowBounds(0, 1), new ResultHandler() {  @Override  public void handleResult(ResultContext resultContext) {  Object obj = resultContext.getResultObject();  System.out.println(obj);  }  });  sqlSession.close();  
}

查询打印结果如下,数据库中有多条记录

TestDemo{demoId=1, demoName='测试名称', demoDesc='测试备注'}

在mybatis插件中可以拦截的方法如下:

  1. Executor类中的update()、query()、flushStatements()、commit()、rollback()、getTransaction()、close()、isClosed()方法;
  2. ParameterHandler类中的getParameterObject()、setParameters()方法;
  3. ResultSetHandler类中的handleResultSets()、handleOu飞putParameters()方法;
  4. StatementHandler类中的prepare()、parameterize()、batch()、update()、query()方法。

总结

Mybatis中的插件实际上就是一个拦截器,Mybatis通过拦截器链来保证每个注册的插件功能都能顺利调用,而且Mybatis通过@Signature注解为我们提供了丰富的可拦截方法,为编写功能丰富的Mybatis扩展创造了条件。当然,想要编写优秀的Mybatis插件还需要对Mybatis的实现原理有更加深入的了解。

到本章为止,关于Mybatis专栏的基础入门相关知识就介绍完了,感谢大家的观看,谢谢🥳🙊😼🦊


📩 联系方式
邮箱:qijilaoli@foxmail.com

❗版权声明
本文为原创文章,版权归作者所有。未经许可,禁止转载。更多内容请访问奇迹老李的博客首页

http://www.lryc.cn/news/269603.html

相关文章:

  • DOA估计算法——迭代自适应算法(IAA)
  • Python If语句以及代码块的基本介绍
  • [嵌入式专栏](FOC - SVPWM扇区计算Part1)
  • 亚马逊美国站ASTM F2613儿童折叠椅和凳子强制性安全标准
  • 【机组期末速成】指令系统|机器指令概述|操作数类型与操作类型|寻址方式|指令格式
  • java美容管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • Redis哨兵
  • 面试算法78:合并排序链表
  • 鸿鹄电子招投标系统:基于Spring Boot、Mybatis、Redis和Layui的企业电子招采平台源码与立项流程
  • node.js对应npm安装和使用
  • (self-supervised learning)Event Camera Data Pre-training
  • 关于个人Git学习记录及相关
  • 【eclipse】eclipse开发springboot项目使用入门
  • Android 13 默认关闭 快速打开相机
  • pytest pytest-html优化样式
  • Visual Studio 配置DLL
  • C/C++转WebAssembly及微信小程序调用
  • 【WPF.NET开发】弱事件模式
  • [Angular] 笔记 16:模板驱动表单 - 选择框与选项
  • Webpack基础使用
  • 扭蛋机小程序搭建:打造互联网“流量池”
  • 解决VNC连接Ubuntu服务器打开终端出现闪退情况
  • flutter是什么
  • GET和POST请求
  • 基于电商场景的高并发RocketMQ实战-Broker写入读取流程性能优化总结、Broker基于Pull模式的主从复制原理
  • 前端DApp开发利器,Ant Design Web3 正式发布 1.0
  • [RoarCTF 2019]Easy Java(java web)
  • Abaqus许可管理策略
  • 对采集到的温湿度数据,使用python进行数据清洗,并使用预测模型进行预测未来一段时间的温湿度数据。
  • 嵌入式SOC之通用图像处理之OSD文字信息叠加的相关实践记录