MyBatis自定義Plugin

做用

官方說明:html

MyBatis 容許你在已映射語句執行過程當中的某一點進行攔截調用。java

什麼意思呢?就是你能夠對執行某些方法以前進行攔截,作本身的一些操做,如:sql

1.記錄全部執行的SQL(經過對 MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法進行攔截)apache

2.修改SQL(org.apache.ibatis.executor.Executor中query方法進行攔截)等。mybatis

但攔截的方法調用有限制,MyBatis 容許使用插件來攔截的方法調用包括:app

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

實現

使用插件是很是簡單的,只需實現 Interceptor 接口,並指定想要攔截的方法簽名便可。this

// ExamplePlugin.java
@Intercepts({@Signature(
  type= Executor.class,
  method = "update",
  args = {MappedStatement.class,Object.class},
  @Signature(
   type = Executor.class, //必須爲上面所支持的類
    method = "query", //類中支持的方法,可從源碼中查看支持哪些方法
    args = {MappedStatement.class, Object.class , RowBounds.class, ResultHandler.class})}) //對應的參數Class,也可從源碼中查看
public class ExamplePlugin implements Interceptor {
  public Object intercept(Invocation invocation) throws Throwable {
  Object[] queryArgs = invocation.getArgs();
    MappedStatement mappedStatement = (MappedStatement) queryArgs[0];
    Object parameter = queryArgs[1];
    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    String sql = boundSql.getSql();//獲取到SQL ,能夠進行調整
    String name = invocation.getMethod().getName();
    queryArgs[1] = 2; //能夠修改參數內容
    System.err.println("攔截的方法名是:" + name);
    return invocation.proceed();
  }
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }
  public void setProperties(Properties properties) {
  }
}

 

在配置文件中註冊插件spa

<!-- mybatis-config.xml -->
<plugins>
  <plugin interceptor="org.mybatis.example.ExamplePlugin">
    <property name="someProperty" value="100"/>
  </plugin>
</plugins>

當咱們調用query方法時,匹配攔截器的方法, 因此會執行攔截器下intercept方法,作本身的處理。插件

參考資料,官網

http://www.mybatis.org/mybatis-3/zh/configuration.html#pluginscode

相關文章
相關標籤/搜索