1. 程式人生 > >MyBatis自定義Plugin

MyBatis自定義Plugin

signature nts commit sed str 指定 strong 你在 SQ

作用

官方說明:

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

MyBatis自定義Plugin