博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis插件开发
阅读量:7246 次
发布时间:2019-06-29

本文共 2017 字,大约阅读时间需要 6 分钟。

1.

插件初始化

MyBATIS是在初始化上下文环境的时候就初始化插件的,我们看到源码:

它最后是把所有的插件按你配置的顺序保存在一个list对象里面。

3、插件的取出:

MyBATIS的插件可以拦截Executor,StatementHandler,ParameterHandler和ResultHandler对象(下简称四大对象)

 

 

4.MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截MyBatis中的哪些内容呢?

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

我们看到了可以拦截Executor接口的部分方法,比如update,query,commit,rollback等方法,还有其他接口的一些方法等。

总体概括为:

  1. 拦截执行器的方法
  2. 拦截参数的处理
  3. 拦截结果集的处理
  4. 拦截Sql语法构建的处理

 

拦截器的使用

拦截器介绍及配置

首先我们看下MyBatis拦截器的接口定义:

public interface Interceptor {  Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); }

比较简单,只有3个方法。 MyBatis默认没有一个拦截器接口的实现类,开发者们可以实现符合自己需求的拦截器。

下面的MyBatis官网的一个拦截器实例:

@Intercepts({
@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { } }

全局xml配置:

这个拦截器拦截Executor接口的update方法(其实也就是SqlSession的新增,删除,修改操作),所有执行executor的update方法都会被该拦截器拦截到。

源码分析

下面我们分析一下这段代码背后的源码。

首先从源头->配置文件开始分析:

XMLConfigBuilder解析MyBatis全局配置文件的pluginElement私有方法:

private void pluginElement(XNode parent) throws Exception {    if (parent != null) { for (XNode child : parent.getChildren()) { String interceptor = child.getStringAttribute("interceptor"); Properties properties = child.getChildrenAsProperties(); Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance(); interceptorInstance.setProperties(properties); configuration.addInterceptor(interceptorInstance); } } }

转载地址:http://knnbm.baihongyu.com/

你可能感兴趣的文章
MPLS 配置步骤
查看>>
Exchange Server 2007灾难恢复(AD+Ex)
查看>>
GRUB2
查看>>
Go性能优化技巧 1/10
查看>>
DNS 域名解析服务器---案例详解
查看>>
疑似电信版GALAXY S4现身官网 或配八核处理器
查看>>
我的Linux生涯之系统语言环境及中文输入法的操作
查看>>
c#获取当前页面名字
查看>>
客户端自动化技术漫谈
查看>>
mysql 优化之 查询
查看>>
TCP协议中的三次握手和四次挥手(图解)
查看>>
YII assets使用
查看>>
未来已来——工作空间 WorkSpace 和物联网 IoT (2)
查看>>
从零开始玩人工智能-机器人服务-05
查看>>
Google API V2申请及Google Map简单应用例子
查看>>
CXF开发WebService客户端
查看>>
实现一个简单的等待进度盘
查看>>
安全、高效、专业 —— 码云企业版
查看>>
PHP全角转半角
查看>>
GetMessage()与PeekMessage(),以及WM_PAINT消息相关
查看>>