如何在MyBatis中自定義Plugin插件

本篇文章給大家分享的是有關(guān)如何在MyBatis中自定義Plugin插件,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

站在用戶的角度思考問題,與客戶深入溝通,找到道縣網(wǎng)站設(shè)計與道縣網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站設(shè)計、做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、域名與空間、網(wǎng)絡(luò)空間、企業(yè)郵箱。業(yè)務(wù)覆蓋道縣地區(qū)。

MyBatis 允許你在已映射語句執(zhí)行過程中的某一點(diǎn)進(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插件,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

標(biāo)題名稱:如何在MyBatis中自定義Plugin插件
分享URL:http://bm7419.com/article38/jccjsp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、動態(tài)網(wǎng)站網(wǎng)頁設(shè)計公司、靜態(tài)網(wǎng)站、App開發(fā)、App設(shè)計

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司