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

网站开发系统线上教育培训机构十大排名

网站开发系统,线上教育培训机构十大排名,现在建站好么,招商网站如何做推广专栏精选 引入Mybatis Mybatis的快速入门 Mybatis的增删改查扩展功能说明 mapper映射的参数和结果 Mybatis复杂类型的结果映射 Mybatis基于注解的结果映射 Mybatis枚举类型处理和类型处理器 再谈动态SQL Mybatis配置入门 Mybatis行为配置之Ⅰ—缓存 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.hengruixuexiao.com/news/45909.html

相关文章:

  • 泉州专业网站开发公司艾滋病多长时间能查出来
  • 网站界面设计案例教程广告代运营公司
  • 深圳市网站哪家做的好百度贴吧热线客服24小时
  • 四平市建设局网站营业推广的方式有哪些
  • 工商网查询官网网站优化推广招聘
  • 做网站一般需要什么百度自动搜索关键词软件
  • 网页设计与网页制作课程总结seo型网站
  • 哪有专做飞织鞋面的网站哈尔滨关键词排名工具
  • 马和人做人和牛做网站网页制作的基本步骤
  • 山西省建设局网站长沙网红奶茶
  • 饮料企业哪个网站做的比较好html制作网页代码
  • 检测网站是否为WordPress网站优化是做什么的
  • 扶贫基金会网站建设是哪家公司整站优化 mail
  • 上饶网站建设srsemsem是什么?
  • 西安网站开发高端网站开发品牌策划
  • 做期货苯乙烯的网站网店运营工作内容
  • 广东住房和城乡建设委员会网站西安外包网络推广
  • 东营网站建设价钱表cnzz统计
  • 毕节网站开发黑龙江seo关键词优化工具
  • 江苏靖江苏源建设有限公司网站百度咨询
  • 珠市口网站建设百度搜索推广费用
  • 英文成品网站模板下载百度人工客服在线咨询电话
  • 珲春建设银行网站电商网站设计
  • 临沂网站域名百度权重怎么看
  • 100m的网站 数据库网站一键收录
  • 宿迁公司做网站seo标题优化导师咨询
  • 深圳wordpress外贸网站建设网络舆情分析师
  • 用自己电脑做主机做网站长尾词挖掘工具
  • 企业网站推广的方法有搜索引擎推广磁力宝
  • 个人网站每年要多少钱百度云网盘免费资源