詳解MyBatis自定義Plugin插件
作用
官方說(shuō)明:
MyBatis 允許你在已映射語(yǔ)句執(zhí)行過(guò)程中的某一點(diǎn)進(jìn)行攔截調(diào)用。
什么意思呢?就是你可以對(duì)執(zhí)行某些方法之前進(jìn)行攔截,做自己的一些操作,如:
1.記錄所有執(zhí)行的SQL(通過(guò)對(duì) MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法進(jìn)行攔截)
2.修改SQL(org.apache.ibatis.executor.Executor中query方法進(jìn)行攔截)等。
但攔截的方法調(diào)用有限制,MyBatis 允許使用插件來(lái)攔截的方法調(diào)用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
實(shí)現(xiàn)
使用插件是非常簡(jiǎn)單的,只需實(shí)現(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})}) //對(duì)應(yīng)的參數(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 ,可以進(jìn)行調(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) {
}
}
在配置文件中注冊(cè)插件
<!-- mybatis-config.xml --> <plugins> <plugin interceptor="org.mybatis.example.ExamplePlugin"> <property name="someProperty" value="100"/> </plugin> </plugins>
當(dāng)我們調(diào)用query方法時(shí),匹配攔截器的方法, 所以會(huì)執(zhí)行攔截器下intercept方法,做自己的處理。
參考資料,官網(wǎng)
http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins
總結(jié)
以上所述是小編給大家介紹的MyBatis自定義Plugin插件,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
基于eclipse.ini內(nèi)存設(shè)置的問(wèn)題詳解
本篇文章是對(duì)eclipse.ini內(nèi)存設(shè)置的問(wèn)題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
淺談java中null是什么,以及使用中要注意的事項(xiàng)
下面小編就為大家?guī)?lái)一篇淺談java中null是什么,以及使用中要注意的事項(xiàng)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
基于Java實(shí)現(xiàn)Redis多級(jí)緩存方案
這篇文章主要介紹了Redis多級(jí)緩存方案分享,傳統(tǒng)緩存方案、多級(jí)緩存方案、JVM本地緩存,舉例說(shuō)明這些方案,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-03-03
JAVA實(shí)戰(zhàn)項(xiàng)目實(shí)現(xiàn)客戶選購(gòu)系統(tǒng)詳細(xì)流程
讀萬(wàn)卷書不如行萬(wàn)里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的客戶選購(gòu)系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2021-10-10

