Mybatis超具体插件机制理会,弄懂拦截器So easy
副问题[/!--empirenews.page--]
概述 Mybatis插件又称拦截器,本篇文章中呈现的拦截器都暗示插件。 Mybatis回收责任链模式,通过动态署理组织多个插件(拦截器),通过这些插件可以改变Mybatis的默认举动(诸如SQL重写之类的),因为插件会深入到Mybatis的焦点,因此在编写本身的插件前最好相识下它的道理,以便写出安详高效的插件。 MyBatis 应承你在已映射语句执行进程中的某一点举办拦截挪用。默认环境下,MyBatis 应承行使插件来拦截的要领挪用包罗: Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) ParameterHandler (getParameterObject, setParameters) ResultSetHandler (handleResultSets, handleOutputParameters) StatementHandler (prepare, parameterize, batch, update, query) 总体归纳综合为: 拦截执行器的要领 拦截参数的处理赏罚 拦截功效集的处理赏罚 拦截Sql语法构建的处理赏罚 Mybatis是通过动态署理的方法实现拦截的,阅读此篇文章必要先对Java的动态署理机制有所相识。 Mybatis四大接口 既然Mybatis是对四大接口举办拦截的,那我们先要知道Mybatis的四大接口是哪些: Executor, StatementHandler, ResultSetHandler, ParameterHandler。 上图Mybatis框架的整个执行进程。Mybatis插件可以或许对这四大工具举办拦截,可以说包括到了Mybatis一次SQL执行的全部操纵。可见Mybatis的的插件很强盛。 Executor是 Mybatis的内部执行器,它认真挪用StatementHandler操纵数据库,并把功效集通过 ResultSetHandler举办自动映射,其它,他还处理赏罚了二级缓存的操纵。从这里可以看出,我们也是可以通过插件来实现自界说的二级缓存的。 StatementHandler是Mybatis直接和数据库执行sql剧本的工具。其它它也实现了Mybatis的一级缓存。这里,我们可以行使插件来实现对一级缓存的操纵(禁用等等)。 ParameterHandler是Mybatis实现Sql入参配置的工具。插件可以改变我们Sql的参数默认配置。 ResultSetHandler是Mybatis把ResultSet荟萃映射成POJO的接口工具。我们可以界说插件对Mybatis的功效集自动映射举办修改。 插件Interceptor Mybatis的插件实现要实现Interceptor接口,我们看下这个接口界说的要领。 public interface Interceptor { Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); } 这个接口只声明白三个要领: setProperties要领是在Mybatis举办设置插件的时辰可以设置自界说相干属性,即:接话柄现工具的参数设置。 plugin要领是插件用于封装方针工具的,通过该要领我们可以返回方针工具自己,也可以返回一个它的署理,可以抉择是否要举办拦截进而抉摘要返回一个什么样的方针工具,官方提供了示例:return Plugin.wrap(target, this)。 intercept要领就是要举办拦截的时辰要执行的要领。 领略这个接口的界说,先要知道java动态署理机制。plugin接口即返回参数target工具(Executor/ParameterHandler/ResultSetHander/StatementHandler)的署理工具。在挪用对应工具的接口的时辰,可以举办拦截并处理赏罚。 Mybatis四大接口工具建设要领 Mybatis的插件是回收对四大接口的工具天生动态署理工具的要领来实现的。那么此刻我们看下Mybatis是怎么建设这四大接口工具的。 public Executor newExecutor(Transaction transaction, ExecutorType executorType) { //确保ExecutorType不为空(defaultExecutorType有也许为空) executorType = executorType == null ? defaultExecutorType : executorType; executorType = executorType == null ? ExecutorType.SIMPLE : executorType; Executor executor; if (ExecutorType.BATCH == executorType) { executor = new BatchExecutor(this, transaction); } else if (ExecutorType.REUSE == executorType) { executor = new ReuseExecutor(this, transaction); } else { executor = new SimpleExecutor(this, transaction); } if (cacheEnabled) { executor = new CachingExecutor(executor); } executor = (Executor) interceptorChain.pluginAll(executor); return executor; }
(编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |