欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何在Mybatis中實(shí)現(xiàn)一個(gè)Interceptor攔截器

這篇文章將為大家詳細(xì)講解有關(guān)如何在Mybatis中實(shí)現(xiàn)一個(gè)Interceptor 攔截器,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

創(chuàng)新互聯(lián)建站是一家專業(yè)提供復(fù)興企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站建設(shè)、做網(wǎng)站HTML5建站、小程序制作等業(yè)務(wù)。10年已為復(fù)興眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計(jì)公司優(yōu)惠進(jìn)行中。

1. Interceptor

攔截器均需要實(shí)現(xiàn)該 org.apache.ibatis.plugin.Interceptor 接口。

2. Intercepts 攔截器

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})

攔截器的使用需要查看每一個(gè)type所提供的方法參數(shù)。

Signature 對(duì)應(yīng) Invocation 構(gòu)造器,type 為 Invocation.Object,method 為 Invocation.Method,args 為 Invocation.Object[]。

method 對(duì)應(yīng)的 update 包括了最常用的 insert/update/delete 三種操作,因此 update 本身無(wú)法直接判斷sql為何種執(zhí)行過(guò)程。

args 包含了其余所有的操作信息, 按數(shù)組進(jìn)行存儲(chǔ), 不同的攔截方式有不同的參數(shù)順序, 具體看type接口的方法簽名, 然后根據(jù)簽名解析。

3. Object 對(duì)象類型

args 參數(shù)列表中,Object.class 是特殊的對(duì)象類型。如果有數(shù)據(jù)庫(kù)統(tǒng)一的實(shí)體 Entity 類,即包含表公共字段,比如創(chuàng)建、更新操作對(duì)象和時(shí)間的基類等,在編寫(xiě)代碼時(shí)盡量依據(jù)該對(duì)象來(lái)操作,會(huì)簡(jiǎn)單很多。該對(duì)象的判斷使用

Object parameter = invocation.getArgs()[1];
if (parameter instanceof BaseEntity) {
  BaseEntity entity = (BaseEntity) parameter;
}

即可,根據(jù)語(yǔ)句執(zhí)行類型選擇對(duì)應(yīng)字段的賦值。

如果參數(shù)不是實(shí)體,而且具體的參數(shù),那么 Mybatis 也做了一些處理,比如 @Param("name") String name 類型的參數(shù),會(huì)被包裝成 Map 接口的實(shí)現(xiàn)來(lái)處理,即使是原始的 Map 也是如此。使用

Object parameter = invocation.getArgs()[1];
if (parameter instanceof Map) {
  Map map = (Map) parameter;
}

即可,對(duì)具體統(tǒng)一的參數(shù)進(jìn)行賦值。

4. SqlCommandType 命令類型

Executor 提供的方法中,update 包含了 新增,修改和刪除類型,無(wú)法直接區(qū)分,需要借助 MappedStatement 類的屬性 SqlCommandType 來(lái)進(jìn)行判斷,該類包含了所有的操作類型

public enum SqlCommandType {
 UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH;
}

畢竟新增和修改的場(chǎng)景,有些參數(shù)是有區(qū)別的,比如創(chuàng)建時(shí)間和更新時(shí)間,update 時(shí)是無(wú)需兼顧創(chuàng)建時(shí)間字段的。

MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
SqlCommandType commandType = ms.getSqlCommandType();

5. 實(shí)例

自己編寫(xiě)的小項(xiàng)目中,需要統(tǒng)一給數(shù)據(jù)庫(kù)字段屬性賦值:

public class BaseEntity {
  private int id;
  private int creator;
  private int updater;
  private Long createTime;
  private Long updateTime;
}

dao 操作使用了實(shí)體和參數(shù)的方式,個(gè)人建議還是統(tǒng)一使用實(shí)體比較簡(jiǎn)單,易讀。

使用實(shí)體:

int add(BookEntity entity);

使用參數(shù):

復(fù)制代碼 代碼如下:

int update(@Param("id") int id, @Param("url") String url, @Param("description") String description, @Param("playCount") int playCount, @Param("creator") int creator, @Param("updateTime") long updateTime);

完整的例子:

package com.github.zhgxun.talk.common.plugin;

import com.github.zhgxun.talk.common.util.DateUtil;
import com.github.zhgxun.talk.common.util.UserUtil;
import com.github.zhgxun.talk.entity.BaseEntity;
import com.github.zhgxun.talk.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Properties;

/**
 * 全局?jǐn)r截?cái)?shù)據(jù)庫(kù)創(chuàng)建和更新
 * <p>
 * Signature 對(duì)應(yīng) Invocation 構(gòu)造器, type 為 Invocation.Object, method 為 Invocation.Method, args 為 Invocation.Object[]
 * method 對(duì)應(yīng)的 update 包括了最常用的 insert/update/delete 三種操作, 因此 update 本身無(wú)法直接判斷sql為何種執(zhí)行過(guò)程
 * args 包含了其余多有的操作信息, 按數(shù)組進(jìn)行存儲(chǔ), 不同的攔截方式有不同的參數(shù)順序, 具體看type接口的方法簽名, 然后根據(jù)簽名解析, 參見(jiàn)官網(wǎng)
 *
 * @link http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins 插件
 * <p>
 * MappedStatement 包括了SQL具體操作類型, 需要通過(guò)該類型判斷當(dāng)前sql執(zhí)行過(guò)程
 */
@Component
@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class NormalPlugin implements Interceptor {

  @Override
  @SuppressWarnings("unchecked")
  public Object intercept(Invocation invocation) throws Throwable {
    // 根據(jù)簽名指定的args順序獲取具體的實(shí)現(xiàn)類
    // 1. 獲取MappedStatement實(shí)例, 并獲取當(dāng)前SQL命令類型
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    SqlCommandType commandType = ms.getSqlCommandType();

    // 2. 獲取當(dāng)前正在被操作的類, 有可能是Java Bean, 也可能是普通的操作對(duì)象, 比如普通的參數(shù)傳遞
    // 普通參數(shù), 即是 @Param 包裝或者原始 Map 對(duì)象, 普通參數(shù)會(huì)被 Mybatis 包裝成 Map 對(duì)象
    // 即是 org.apache.ibatis.binding.MapperMethod$ParamMap
    Object parameter = invocation.getArgs()[1];
    // 獲取攔截器指定的方法類型, 通常需要攔截 update
    String methodName = invocation.getMethod().getName();
    log.info("NormalPlugin, methodName; {}, commandType: {}", methodName, commandType);

    // 3. 獲取當(dāng)前用戶信息
    UserEntity userEntity = UserUtil.getCurrentUser();
    // 默認(rèn)測(cè)試參數(shù)值
    int creator = 2, updater = 3;

    if (parameter instanceof BaseEntity) {
      // 4. 實(shí)體類
      BaseEntity entity = (BaseEntity) parameter;
      if (userEntity != null) {
        creator = entity.getCreator();
        updater = entity.getUpdater();
      }
      if (methodName.equals("update")) {
        if (commandType.equals(SqlCommandType.INSERT)) {
          entity.setCreator(creator);
          entity.setUpdater(updater);
          entity.setCreateTime(DateUtil.getTimeStamp());
          entity.setUpdateTime(DateUtil.getTimeStamp());
        } else if (commandType.equals(SqlCommandType.UPDATE)) {
          entity.setUpdater(updater);
          entity.setUpdateTime(DateUtil.getTimeStamp());
        }
      }
    } else if (parameter instanceof Map) {
      // 5. @Param 等包裝類
      // 更新時(shí)指定某些字段的最新數(shù)據(jù)值
      if (commandType.equals(SqlCommandType.UPDATE)) {
        // 遍歷參數(shù)類型, 檢查目標(biāo)參數(shù)值是否存在對(duì)象中, 該方式需要應(yīng)用編寫(xiě)有一些統(tǒng)一的規(guī)范
        // 否則均統(tǒng)一為實(shí)體對(duì)象, 就免去該重復(fù)操作
        Map map = (Map) parameter;
        if (map.containsKey("creator")) {
          map.put("creator", creator);
        }
        if (map.containsKey("updateTime")) {
          map.put("updateTime", DateUtil.getTimeStamp());
        }
      }
    }
    // 6. 均不是需要被攔截的類型, 不做操作
    return invocation.proceed();
  }

  @Override
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  @Override
  public void setProperties(Properties properties) {
  }
}

6. 感受

其它幾種類型,后面在看,尤其是分頁(yè)。

在編寫(xiě)代碼的過(guò)程中,有時(shí)候還是需要先知道對(duì)象的類型,比如 Object.class 跟 Interface 一樣,很多時(shí)候僅僅代表一種數(shù)據(jù)類型,需要明確知道后再進(jìn)行操作。

@Param 標(biāo)識(shí)的參數(shù)其實(shí)會(huì)被 Mybatis 封裝成 org.apache.ibatis.binding.MapperMethod$ParamMap 類型,一開(kāi)始我就是使用

for (Field field:parameter.getClass().getDeclaredFields()) {

}

關(guān)于如何在Mybatis中實(shí)現(xiàn)一個(gè)Interceptor 攔截器就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

名稱欄目:如何在Mybatis中實(shí)現(xiàn)一個(gè)Interceptor攔截器
標(biāo)題來(lái)源:http://chinadenli.net/article12/jpchgc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)網(wǎng)站內(nèi)鏈動(dòng)態(tài)網(wǎng)站App設(shè)計(jì)靜態(tài)網(wǎng)站

廣告

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

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司