您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)如何在MyBatis中自定義Plugin插件,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
MyBatis 允許你在已映射語句執(zhí)行過程中的某一點進(jìn)行攔截調(diào)用。
什么意思呢?就是你可以對執(zhí)行某些方法之前進(jìn)行攔截,做自己的一些操作,如:
1.記錄所有執(zhí)行的SQL(通過對 MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法進(jìn)行攔截)
2.修改SQL(org.apache.ibatis.executor.Executor中query方法進(jìn)行攔截)等。
但攔截的方法調(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})}) //對應(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) { } }
在配置文件中注冊插件
<!-- mybatis-config.xml --> <plugins> <plugin interceptor="org.mybatis.example.ExamplePlugin"> <property name="someProperty" value="100"/> </plugin> </plugins>
以上就是如何在MyBatis中自定義Plugin插件,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。