詳解MyBatis自定義Plugin插件
作用
官方說明:
MyBatis 允許你在已映射語句執(zhí)行過程中的某一點進行攔截調(diào)用。
什么意思呢?就是你可以對執(zhí)行某些方法之前進行攔截,做自己的一些操作,如:
1.記錄所有執(zhí)行的SQL(通過對 MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法進行攔截)
2.修改SQL(org.apache.ibatis.executor.Executor中query方法進行攔截)等。
但攔截的方法調(diào)用有限制,MyBatis 允許使用插件來攔截的方法調(diào)用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
實現(xiàn)
使用插件是非常簡單的,只需實現(xiàn) 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})}) //對應的參數(shù)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 ,可以進行調(diào)整 String name = invocation.getMethod().getName(); queryArgs[1] = 2; //可以修改參數(shù)內(nèi)容 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>
當我們調(diào)用query方法時,匹配攔截器的方法, 所以會執(zhí)行攔截器下intercept方法,做自己的處理。
參考資料,官網(wǎng)
http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins
總結(jié)
以上所述是小編給大家介紹的MyBatis自定義Plugin插件,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
使用ClassFinal實現(xiàn)SpringBoot項目jar包加密的操作指南
在實際開發(fā)中,保護項目的安全性和保密性是至關重要的,針對于 Spring Boot 項目,我們需要將 JAR 包進行加密從而有效地防止未經(jīng)授權的訪問和修改,本文將介紹如何使用ClassFinal在 Spring Boot 項目中實現(xiàn) JAR 包加密,需要的朋友可以參考下2024-06-06淺談SpringSecurity注解與AOP切面執(zhí)行順序
這篇文章主要介紹了淺談SpringSecurity注解與AOP切面執(zhí)行順序,引入Spring Security后,在Controller的方法中會出現(xiàn)Spring Security的方法注解與AOP同時存在的問題,這是就會設計順序問題,需要的朋友可以參考下2023-10-10詳解IDEA社區(qū)版(Community)和付費版(UItimate)的區(qū)別
這篇文章主要介紹了詳解IDEA社區(qū)版(Community)和付費版(UItimate)的區(qū)別,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11Spring的異常處理@ExceptionHandler注解解析
這篇文章主要介紹了Spring的異常處理@ExceptionHandler注解解析,當一個Controller中有方法加了@ExceptionHandler之后,這個Controller其他方法中沒有捕獲的異常就會以參數(shù)的形式傳入加了@ExceptionHandler注解的那個方法中,需要的朋友可以參考下2023-12-12Java?SE判斷兩個文件內(nèi)容是否相同的多種方法代碼
昨天因為要幫師兄的忙所以看了一下如何判斷兩個文件內(nèi)容是否相同,這里給大家總結(jié)下,這篇文章主要給大家介紹了關于Java?SE判斷兩個文件內(nèi)容是否相同的多種方法,需要的朋友可以參考下2023-11-11