作用
官方說明:
MyBatis 允許你在已映射語句執行過程中的某一點進行攔截調用。
什麼意思呢?就是你可以對執行某些方法之前進行攔截,做自己的一些操作,如:
1.記錄所有執行的SQL(通過對MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法進行攔截)
2.修改SQL(org.apache.ibatis.executor.Executor中query方法進行攔截)等。
但攔截的方法調用有限制,MyBatis 允許使用插件來攔截的方法調用包括:
實現
使用插件是非常簡單的,只需實現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插件,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!