MyBatis原理-拦截器
一、MyBatis拦截器介绍
MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能。
MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
我们看到了可以拦截Executor接口的部分方法,比如update,query,commit,rollback等方法,还有其他接口的一些方法等。
总体概括为:
- 拦截执行器的方法
- 拦截参数的处理
- 拦截结果集的处理
- 拦截Sql语法构建的处理
二、拦截器的使用
MyBatis拦截器的接口定义:
package org.apache.ibatis.plugin; import java.util.Properties; /** * @author Clinton Begin */ public interface Interceptor { Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); }
下面的MyBatis官网的一个拦截器实例:
@Intercepts({@Signature( type= Executor.class, method = "update", // 拦截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配置:
<plugins> <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin> </plugins>
分页插件PageHelper配置
<!-- 配置mybatis的分页插件PageHelper --> <plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 设置数据库类型Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 --> <property name="dialect" value="mysql"/> </plugin> </plugins>
springboot的PageHelper配置
//配置mybatis的分页插件pageHelper 2 @Bean 3 public PageHelper pageHelper(){ 4 PageHelper pageHelper = new PageHelper(); 5 Properties properties = new Properties(); 6 properties.setProperty("offsetAsPageNum","true"); 7 properties.setProperty("rowBoundsWithCount","true"); 8 properties.setProperty("reasonable","true"); 9 properties.setProperty("dialect","mysql"); //配置mysql数据库的方言 10 pageHelper.setProperties(properties); 11 return pageHelper; 12 }
这个拦截器拦截Executor接口的update方法(其实也就是SqlSession的新增,删除,修改操作),所有执行executor的update方法都会被该拦截器拦截到。