Mybatis插件入门

专栏精选

引入Mybatis

Mybatis的快速入门

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

mapper映射的参数和结果

Mybatis复杂类型的结果映射

Mybatis基于注解的结果映射

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

再谈动态SQL

Mybatis配置入门

Mybatis行为配置之Ⅰ—缓存

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

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

Mybatis行为配置之Ⅳ—日志

Mybatis整合Spring详解

Mybatis插件入门

Mybatis专栏代码资源

引言

大家好,我是奇迹老李,一个专注于分享开发经验和基础教程的博主。欢迎来到我的频道,这里汇聚了汇集编程技巧、代码示例和技术教程,欢迎广大朋友们点赞评论提出意见,重要的是点击关注喔 🙆,期待在这里与你共同度过美好的时光🕹️。今天要和大家分享的内容是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);

  @Override
  public 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);
    }
  }

  @Override
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  @Override
  public 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

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

  • 19
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李奇技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值