作用
官方說明:
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 接口,并指定想要攔截的方法簽名即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// 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) { } } |
在配置文件中注冊插件
1
2
3
4
5
6
|
<!-- 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插件,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/lhl5230/archive/2018/05/31/9119601.html