攔截器(Interceptor)在 Mybatis 中被當作插件(plugin)對待,官方文檔提供了 Executor(攔截執行器的方法),ParameterHandler(攔截參數的處理),ResultSetHandler(攔截結果集的處理),StatementHandler(攔截Sql語法構建的處理) 共4種,而且提示「這些類中方法的細節能夠經過查看每一個方法的簽名來發現,或者直接查看 MyBatis 發行包中的源代碼」。html
攔截器的使用場景主要是更新數據庫的通用字段,分庫分表,加解密等的處理。java
攔截器均須要實現該 org.apache.ibatis.plugin.Interceptor
接口。git
@Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) })
攔截器的使用須要查看每個type所提供的方法參數。github
Signature 對應 Invocation 構造器,type 爲 Invocation.Object,method 爲 Invocation.Method,args 爲 Invocation.Object[]。spring
method 對應的 update 包括了最經常使用的 insert/update/delete 三種操做,所以 update 自己沒法直接判斷sql爲什麼種執行過程。sql
args 包含了其他全部的操做信息, 按數組進行存儲, 不一樣的攔截方式有不一樣的參數順序, 具體看type接口的方法簽名, 而後根據簽名解析。數據庫
args 參數列表中,Object.class 是特殊的對象類型。若是有數據庫統一的實體 Entity 類,即包含表公共字段,好比建立、更新操做對象和時間的基類等,在編寫代碼時儘可能依據該對象來操做,會簡單不少。該對象的判斷使用apache
Object parameter = invocation.getArgs()[1]; if (parameter instanceof BaseEntity) { BaseEntity entity = (BaseEntity) parameter; }
便可,根據語句執行類型選擇對應字段的賦值。數組
若是參數不是實體,並且具體的參數,那麼 Mybatis 也作了一些處理,好比 @Param("name") String name
類型的參數,會被包裝成 Map
接口的實現來處理,即便是原始的 Map
也是如此。使用mybatis
Object parameter = invocation.getArgs()[1]; if (parameter instanceof Map) { Map map = (Map) parameter; }
便可,對具體統一的參數進行賦值。
Executor
提供的方法中,update
包含了 新增,修改和刪除類型,沒法直接區分,須要藉助 MappedStatement
類的屬性 SqlCommandType
來進行判斷,該類包含了全部的操做類型
public enum SqlCommandType { UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH; }
畢竟新增和修改的場景,有些參數是有區別的,好比建立時間和更新時間,update
時是無需兼顧建立時間字段的。
MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; SqlCommandType commandType = ms.getSqlCommandType();
本身編寫的小項目中,須要統一給數據庫字段屬性賦值:
public class BaseEntity { private int id; private int creator; private int updater; private Long createTime; private Long updateTime; }
dao 操做使用了實體和參數的方式,我的建議仍是統一使用實體比較簡單,易讀。
使用實體:
int add(BookEntity entity);
使用參數:
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; /** * 全局攔截數據庫建立和更新 * <p> * Signature 對應 Invocation 構造器, type 爲 Invocation.Object, method 爲 Invocation.Method, args 爲 Invocation.Object[] * method 對應的 update 包括了最經常使用的 insert/update/delete 三種操做, 所以 update 自己沒法直接判斷sql爲什麼種執行過程 * args 包含了其他多有的操做信息, 按數組進行存儲, 不一樣的攔截方式有不一樣的參數順序, 具體看type接口的方法簽名, 而後根據簽名解析, 參見官網 * * @link http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins 插件 * <p> * MappedStatement 包括了SQL具體操做類型, 須要經過該類型判斷當前sql執行過程 */ @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 { // 根據簽名指定的args順序獲取具體的實現類 // 1. 獲取MappedStatement實例, 並獲取當前SQL命令類型 MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; SqlCommandType commandType = ms.getSqlCommandType(); // 2. 獲取當前正在被操做的類, 有多是Java Bean, 也多是普通的操做對象, 好比普通的參數傳遞 // 普通參數, 便是 @Param 包裝或者原始 Map 對象, 普通參數會被 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. 獲取當前用戶信息 UserEntity userEntity = UserUtil.getCurrentUser(); // 默認測試參數值 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 等包裝類 // 更新時指定某些字段的最新數據值 if (commandType.equals(SqlCommandType.UPDATE)) { // 遍歷參數類型, 檢查目標參數值是否存在對象中, 該方式須要應用編寫有一些統一的規範 // 不然均統一爲實體對象, 就免去該重複操做 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) { } }
其它幾種類型,後面在看,尤爲是分頁。
在編寫代碼的過程當中,有時候仍是須要先知道對象的類型,好比 Object.class 跟 Interface 同樣,不少時候僅僅表明一種數據類型,須要明確知道後再進行操做。
@Param
標識的參數其實會被 Mybatis 封裝成 org.apache.ibatis.binding.MapperMethod$ParamMap
類型,一開始我就是使用
for (Field field:parameter.getClass().getDeclaredFields()) { }
的方式獲取,覺得這些都是對象的屬性,經過反射獲取並修改便可,實際上發現對象不存在這些屬性,可是打印出的信息中,明確有這些字段的,網上參考一些信息後,才知道這是一個 Map
類型,問題才迎刃而解。
可參考MyBatis攔截器原理探究。