Mybatis Interceptor 攔截器的實現(xiàn)
Mybatis采用責(zé)任鏈模式,通過動態(tài)代理組織多個攔截器(插件),通過這些攔截器可以改變Mybatis的默認行為(諸如SQL重寫之類的),由于插件會深入到Mybatis的核心,因此在編寫自己的插件前最好了解下它的原理,以便寫出安全高效的插件。
攔截器(Interceptor)在 Mybatis 中被當(dāng)做插件(plugin)對待,官方文檔提供了 Executor,ParameterHandler,ResultSetHandler,StatementHandler 共4種,并且提示“這些類中方法的細節(jié)可以通過查看每個方法的簽名來發(fā)現(xiàn),或者直接查看 MyBatis 發(fā)行包中的源代碼”。
攔截器的使用場景主要是更新數(shù)據(jù)庫的通用字段,分庫分表,加解密等的處理。
1. Interceptor
攔截器均需要實現(xiàn)該 org.apache.ibatis.plugin.Interceptor 接口。
2. Intercepts 攔截器
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
攔截器的使用需要查看每一個type所提供的方法參數(shù)。
Signature 對應(yīng) Invocation 構(gòu)造器,type 為 Invocation.Object,method 為 Invocation.Method,args 為 Invocation.Object[]。
method 對應(yīng)的 update 包括了最常用的 insert/update/delete 三種操作,因此 update 本身無法直接判斷sql為何種執(zhí)行過程。
args 包含了其余所有的操作信息, 按數(shù)組進行存儲, 不同的攔截方式有不同的參數(shù)順序, 具體看type接口的方法簽名, 然后根據(jù)簽名解析。
3. Object 對象類型
args 參數(shù)列表中,Object.class 是特殊的對象類型。如果有數(shù)據(jù)庫統(tǒng)一的實體 Entity 類,即包含表公共字段,比如創(chuàng)建、更新操作對象和時間的基類等,在編寫代碼時盡量依據(jù)該對象來操作,會簡單很多。該對象的判斷使用
Object parameter = invocation.getArgs()[1];
if (parameter instanceof BaseEntity) {
BaseEntity entity = (BaseEntity) parameter;
}
即可,根據(jù)語句執(zhí)行類型選擇對應(yīng)字段的賦值。
如果參數(shù)不是實體,而且具體的參數(shù),那么 Mybatis 也做了一些處理,比如 @Param("name") String name 類型的參數(shù),會被包裝成 Map 接口的實現(xiàn)來處理,即使是原始的 Map 也是如此。使用
Object parameter = invocation.getArgs()[1];
if (parameter instanceof Map) {
Map map = (Map) parameter;
}
即可,對具體統(tǒng)一的參數(shù)進行賦值。
4. SqlCommandType 命令類型
Executor 提供的方法中,update 包含了 新增,修改和刪除類型,無法直接區(qū)分,需要借助 MappedStatement 類的屬性 SqlCommandType 來進行判斷,該類包含了所有的操作類型
public enum SqlCommandType {
UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH;
}
畢竟新增和修改的場景,有些參數(shù)是有區(qū)別的,比如創(chuàng)建時間和更新時間,update 時是無需兼顧創(chuàng)建時間字段的。
MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; SqlCommandType commandType = ms.getSqlCommandType();
5. 實例
自己編寫的小項目中,需要統(tǒng)一給數(shù)據(jù)庫字段屬性賦值:
public class BaseEntity {
private int id;
private int creator;
private int updater;
private Long createTime;
private Long updateTime;
}
dao 操作使用了實體和參數(shù)的方式,個人建議還是統(tǒng)一使用實體比較簡單,易讀。
使用實體:
int add(BookEntity entity);
使用參數(shù):
完整的例子:
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;
/**
* 全局攔截數(shù)據(jù)庫創(chuàng)建和更新
* <p>
* Signature 對應(yīng) Invocation 構(gòu)造器, type 為 Invocation.Object, method 為 Invocation.Method, args 為 Invocation.Object[]
* method 對應(yīng)的 update 包括了最常用的 insert/update/delete 三種操作, 因此 update 本身無法直接判斷sql為何種執(zhí)行過程
* args 包含了其余多有的操作信息, 按數(shù)組進行存儲, 不同的攔截方式有不同的參數(shù)順序, 具體看type接口的方法簽名, 然后根據(jù)簽名解析, 參見官網(wǎng)
*
* @link http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins 插件
* <p>
* MappedStatement 包括了SQL具體操作類型, 需要通過該類型判斷當(dāng)前sql執(zhí)行過程
*/
@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順序獲取具體的實現(xiàn)類
// 1. 獲取MappedStatement實例, 并獲取當(dāng)前SQL命令類型
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
SqlCommandType commandType = ms.getSqlCommandType();
// 2. 獲取當(dāng)前正在被操作的類, 有可能是Java Bean, 也可能是普通的操作對象, 比如普通的參數(shù)傳遞
// 普通參數(shù), 即是 @Param 包裝或者原始 Map 對象, 普通參數(shù)會被 Mybatis 包裝成 Map 對象
// 即是 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();
// 默認測試參數(shù)值
int creator = 2, updater = 3;
if (parameter instanceof BaseEntity) {
// 4. 實體類
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ù)據(jù)值
if (commandType.equals(SqlCommandType.UPDATE)) {
// 遍歷參數(shù)類型, 檢查目標(biāo)參數(shù)值是否存在對象中, 該方式需要應(yīng)用編寫有一些統(tǒng)一的規(guī)范
// 否則均統(tǒng)一為實體對象, 就免去該重復(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. 感受
其它幾種類型,后面在看,尤其是分頁。
在編寫代碼的過程中,有時候還是需要先知道對象的類型,比如 Object.class 跟 Interface 一樣,很多時候僅僅代表一種數(shù)據(jù)類型,需要明確知道后再進行操作。
@Param 標(biāo)識的參數(shù)其實會被 Mybatis 封裝成 org.apache.ibatis.binding.MapperMethod$ParamMap 類型,一開始我就是使用
for (Field field:parameter.getClass().getDeclaredFields()) {
}
的方式獲取,以為這些都是對象的屬性,通過反射獲取并修改即可,實際上發(fā)現(xiàn)對象不存在這些屬性,但是打印出的信息中,明確有這些字段的,網(wǎng)上參考一些信息后,才知道這是一個 Map 類型,問題才迎刃而解。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java利用ElasticSearch實現(xiàn)自動補全功能
這篇文章主要為大家詳細介紹了Java如何利用ElasticSearch實現(xiàn)跟谷歌和百度類似的下拉補全提示功能,文中的示例代碼講解詳細,需要的可以參考一下2023-08-08
java arrayList遍歷的四種方法及Java中ArrayList類的用法
arraylist是動態(tài)數(shù)組,它具有三個好處分別是:動態(tài)的增加和減少元素 、實現(xiàn)了ICollection和IList接口、靈活的設(shè)置數(shù)組的大小,本文給大家介紹java arraylist遍歷及Java arraylist 用法,感興趣的朋友一起學(xué)習(xí)吧2015-11-11
Java中DataInputStream和DataOutputStream的使用方法
這篇文章主要介紹了Java中DataInputStream和DataOutputStream的使用方法,通過創(chuàng)建對象展開具體的內(nèi)容介紹,需要的小伙伴可以參考一下2022-05-05
解決啟用 Spring-Cloud-OpenFeign 配置可刷新項目無法啟動的問題
這篇文章主要介紹了解決啟用 Spring-Cloud-OpenFeign 配置可刷新項目無法啟動的問題,本文重點給大家介紹Spring-Cloud-OpenFeign的原理及問題解決方法,需要的朋友可以參考下2021-10-10

