MyBatis自定義Plugin


作用

官方說明:

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

什么意思呢?就是你可以對執行某些方法之前進行攔截,做自己的一些操作,如:

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

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

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

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

實現

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

// 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) {
  }
}

 

在配置文件中注冊插件

<!-- 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#plugins

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM