學(xué)好Java?MyBatis攔截器,提高工作效率
場景:
在后端服務(wù)開發(fā)時,現(xiàn)在很流行的框架組合就是SSM(SpringBoot + Spring + MyBatis),在我們進行一些業(yè)務(wù)系統(tǒng)開發(fā)時,會有很多的業(yè)務(wù)數(shù)據(jù)表,而表中的信息從新插入開始,整個生命周期過程中可能會進行很多次的操作。
比如:我們在某網(wǎng)站購買一件商品,會生成一條訂單記錄,在支付完金額后訂單狀態(tài)會變?yōu)橐阎Ц?,等最后我們收到訂單商品,這個訂單狀態(tài)會變成已完成等。
假設(shè)我們的訂單表t_order結(jié)果如下:
當(dāng)訂單創(chuàng)建時,需要設(shè)置insert_by,insert_time,update_by,update_time
的值;
在進行訂單狀態(tài)更新時,則只需要更新update_by,update_time
的值。
那應(yīng)該如何處理呢?
1.麻瓜做法
最簡單的做法,也是最容易想到的做法,就是在每個業(yè)務(wù)處理的代碼中,對相關(guān)的字段進行處理。
比如訂單創(chuàng)建的方法中,如下處理:
public void create(Order order){ ? ? // ...其他代碼 ? ? // 設(shè)置審計字段 ? ? Date now = new Date(); ? ? order.setInsertBy(appContext.getUser()); ? ? order.setUpdateBy(appContext.getUser()); ? ? order.setInsertTime(now); ? ? order.setUpdateTime(now); ? ? orderDao.insert(order); }
訂單更新方法則只設(shè)置updateBy和updateTime:
public void update(Order order){ ? ? // ...其他代碼 ? ? // 設(shè)置審計字段 ? ? Date now = new Date(); ? ? order.setUpdateBy(appContext.getUser()); ? ? order.setUpdateTime(now); ? ? orderDao.insert(order); }
這種方式雖然可以完成功能,但是存在一些問題:
需要在每個方法中按照不同的業(yè)務(wù)邏輯決定設(shè)置哪些字段;
在業(yè)務(wù)模型變多后,每個模型的業(yè)務(wù)方法中都要進行設(shè)置,重復(fù)代碼太多。
那我們知道這種方式存在問題以后,就得找找有什么好方法對不對,往下看!
2.優(yōu)雅做法
因為我們持久層框架更多地使用MyBatis
,那我們就借助于MyBatis的攔截器來完成我們的功能。
首先我們來了解一下,什么是攔截器?
3.什么是攔截器?
MyBatis的攔截器顧名思義,就是對某些操作進行攔截。通過攔截器可以對某些方法執(zhí)行前后進行攔截,添加一些處理邏輯。
MyBatis的攔截器可以對Executor
、StatementHandler
、PameterHandler
和ResultSetHandler
接口進行攔截,也就是說會對這4種對象進行代理。
攔截器設(shè)計的初衷就是為了讓用戶在MyBatis的處理流程中不必去修改MyBatis的源碼,能夠以插件的方式集成到整個執(zhí)行流程中。
比如MyBatis
中的Executor
有BatchExecutor
、ReuseExecutor
、SimpleExecutor
和CachingExecutor
,如果這幾種實現(xiàn)的query方法都不能滿足你的需求,我們可以不用去直接修改MyBatis的源碼,而通過建立攔截器的方式,攔截Executor接口的query方法,在攔截之后,實現(xiàn)自己的query方法邏輯。
在MyBatis中的攔截器通過Interceptor
接口表示,該接口中有三個方法。
public interface Interceptor { ? Object intercept(Invocation invocation) throws Throwable; ? Object plugin(Object target); ? void setProperties(Properties properties); }
plugin
方法是攔截器用于封裝目標(biāo)對象的,通過該方法我們可以返回目標(biāo)對象本身,也可以返回一個它的代理。
當(dāng)返回的是代理的時候我們可以對其中的方法進行攔截來調(diào)用intercept
方法,當(dāng)然也可以調(diào)用其他方法。
setProperties
方法是用于在Mybatis配置文件中指定一些屬性的。
4.使用攔截器更新審計字段
那么我們應(yīng)該如何通過攔截器來實現(xiàn)我們對審計字段賦值的功能呢?
在我們進行訂單創(chuàng)建和修改時,本質(zhì)上是通過MyBatis執(zhí)行insert、update語句,MyBatis是通過Executor來處理的。
我們可以通過攔截器攔截Executor,然后在攔截器中對要插入的數(shù)據(jù)對象根據(jù)執(zhí)行的語句設(shè)置insert_by,insert_time,update_by,update_time等屬性值就可以了。
5.自定義攔截器
自定義Interceptor
最重要的是要實現(xiàn)plugin
方法和intercept
方法。
在plugin方法中我們可以決定是否要進行攔截進而決定要返回一個什么樣的目標(biāo)對象。
在intercept方法就是要進行攔截的時候要執(zhí)行的方法。
對于plugin方法而言,其實Mybatis已經(jīng)為我們提供了一個實現(xiàn)。Mybatis中有一個叫做Plugin的類,里面有一個靜態(tài)方法wrap(Object target,Interceptor interceptor),通過該方法可以決定要返回的對象是目標(biāo)對象還是對應(yīng)的代理。
但是這里還存在一個問題,就是我們?nèi)绾卧跀r截器中知道要插入的表有審計字段需要處理呢?
因為我們的表中并不是所有的表都是業(yè)務(wù)表,可能有一些字典表或者定義表是沒有審計字段的,這樣的表我們不需要在攔截器中進行處理。
也就是說我們要能夠區(qū)分出哪些對象需要更新審計字段。
這里我們可以定義一個接口,讓需要更新審計字段的模型都統(tǒng)一實現(xiàn)該接口,這個接口起到一個標(biāo)記的作用。
public interface BaseDO { } public class Order implements BaseDO{ ? ? private Long orderId; ? ? private String orderNo; ? ? private Integer orderStatus; ? ? private String insertBy; ? ? private String updateBy; ? ? private Date insertTime; ? ? private Date updateTime; ? ? //... getter ,setter }
接下來,我們就可以實現(xiàn)我們的自定義攔截器了。
@Component("ibatisAuditDataInterceptor") @Intercepts({@Signature(method = "update", type = Executor.class, args = {MappedStatement.class, Object.class})}) public class IbatisAuditDataInterceptor implements Interceptor { ? ? private Logger logger = LoggerFactory.getLogger(IbatisAuditDataInterceptor.class); ? ? @Override ? ? public Object intercept(Invocation invocation) throws Throwable { ? ? ? ? // 從上下文中獲取用戶名 ? ? ? ? String userName = AppContext.getUser(); ? ? ? ?? ? ? ? ? Object[] args = invocation.getArgs(); ? ? ? ? SqlCommandType sqlCommandType = null; ? ? ? ?? ? ? ? ? for (Object object : args) { ? ? ? ? ? ? // 從MappedStatement參數(shù)中獲取到操作類型 ? ? ? ? ? ? if (object instanceof MappedStatement) { ? ? ? ? ? ? ? ? MappedStatement ms = (MappedStatement) object; ? ? ? ? ? ? ? ? sqlCommandType = ms.getSqlCommandType(); ? ? ? ? ? ? ? ? logger.debug("操作類型: {}", sqlCommandType); ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? } ? ? ? ? ? ? // 判斷參數(shù)是否是BaseDO類型 ? ? ? ? ? ? // 一個參數(shù) ? ? ? ? ? ? if (object instanceof BaseDO) { ? ? ? ? ? ? ? ? if (SqlCommandType.INSERT == sqlCommandType) { ? ? ? ? ? ? ? ? ? ? Date insertTime = new Date(); ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(object, "insertedBy", userName); ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(object, "insertTimestamp", insertTime); ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(object, "updatedBy", userName); ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(object, "updateTimestamp", insertTime); ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? if (SqlCommandType.UPDATE == sqlCommandType) { ? ? ? ? ? ? ? ? ? ? Date updateTime = new Date(); ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(object, "updatedBy", userName); ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(object, "updateTimestamp", updateTime); ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? // 兼容MyBatis的updateByExampleSelective(record, example); ? ? ? ? ? ? if (object instanceof ParamMap) { ? ? ? ? ? ? ? ? logger.debug("mybatis arg: {}", object); ? ? ? ? ? ? ? ? @SuppressWarnings("unchecked") ? ? ? ? ? ? ? ? ParamMap<Object> parasMap = (ParamMap<Object>) object; ? ? ? ? ? ? ? ? String key = "record"; ? ? ? ? ? ? ? ? if (!parasMap.containsKey(key)) { ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? Object paraObject = parasMap.get(key); ? ? ? ? ? ? ? ? if (paraObject instanceof BaseDO) { ? ? ? ? ? ? ? ? ? ? if (SqlCommandType.UPDATE == sqlCommandType) { ? ? ? ? ? ? ? ? ? ? ? ? Date updateTime = new Date(); ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(paraObject, "updatedBy", userName); ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(paraObject, "updateTimestamp", updateTime); ? ? ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? // 兼容批量插入 ? ? ? ? ? ? if (object instanceof DefaultSqlSession.StrictMap) { ? ? ? ? ? ? ? ? logger.debug("mybatis arg: {}", object); ? ? ? ? ? ? ? ? @SuppressWarnings("unchecked") ? ? ? ? ? ? ? ? DefaultSqlSession.StrictMap<ArrayList<Object>> map = (DefaultSqlSession.StrictMap<ArrayList<Object>>) object; ? ? ? ? ? ? ? ? String key = "collection"; ? ? ? ? ? ? ? ? if (!map.containsKey(key)) { ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ArrayList<Object> objs = map.get(key); ? ? ? ? ? ? ? ? for (Object obj : objs) { ? ? ? ? ? ? ? ? ? ? if (obj instanceof BaseDO) { ? ? ? ? ? ? ? ? ? ? ? ? if (SqlCommandType.INSERT == sqlCommandType) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? Date insertTime = new Date(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(obj, "insertedBy", userName); ? ? ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(obj, "insertTimestamp", insertTime); ? ? ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(obj, "updatedBy", userName); ? ? ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(obj, "updateTimestamp", insertTime); ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? if (SqlCommandType.UPDATE == sqlCommandType) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? Date updateTime = new Date(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(obj, "updatedBy", userName); ? ? ? ? ? ? ? ? ? ? ? ? ? ? BeanUtils.setProperty(obj, "updateTimestamp", updateTime); ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return invocation.proceed(); ? ? } ? ? @Override ? ? public Object plugin(Object target) { ? ? ? ? return Plugin.wrap(target, this); ? ? } ? ? @Override ? ? public void setProperties(Properties properties) { ? ? } }
通過上面的代碼可以看到,我們自定義的攔截器IbatisAuditDataInterceptor
實現(xiàn)了Interceptor
接口。
在我們攔截器上的@Intercepts
注解,type參數(shù)指定了攔截的類是Executor
接口的實現(xiàn),method 參數(shù)指定攔截Executor中的update方法,因為數(shù)據(jù)庫操作的增刪改操作都是通過update方法執(zhí)行。
6.配置攔截器插件
在定義好攔截器之后,需要將攔截器指定到SqlSessionFactoryBean
的plugins
中才能生效。所以要按照如下方式配置。
<bean id="transSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> ? ? <property name="dataSource" ref="transDataSource" /> ? ? <property name="mapperLocations"> ? ? ? ? <array> ? ? ? ? ? ? <value>classpath:META-INF/mapper/*.xml</value> ? ? ? ? </array> ? ? </property> ? ? <property name="plugins"> ? ? ? ? <array> ? ? ? ? ? ? <!-- 處理審計字段 --> ? ? ? ? ? ? <ref bean="ibatisAuditDataInterceptor" /> ? ? ? ? </array> ? ? </property>
到這里,我們自定義的攔截器就生效了,通過測試你會發(fā)現(xiàn),不用在業(yè)務(wù)代碼中手動設(shè)置審計字段的值,會在事務(wù)提交之后,通過攔截器插件自動對審計字段進行賦值。
小結(jié):
在本期內(nèi)容中小黑給大家介紹了對于我們?nèi)粘i_發(fā)中很頻繁的審計字段的更新操作,應(yīng)該如何優(yōu)雅地處理。
通過自定義MyBatis
的攔截器,以插件的形式對一些有審計字段的業(yè)務(wù)模型自動賦值,避免重復(fù)編寫枯燥的重復(fù)代碼。
到此這篇關(guān)于學(xué)好Java MyBatis攔截器,提高工作效率的文章就介紹到這了,更多相關(guān)Java MyBatis攔截器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
maven安裝、使用、配置本地倉庫、idea配置maven以及解決plugins報錯問題
本地倉庫是遠(yuǎn)程倉庫的一個緩沖和子集,當(dāng)你構(gòu)建Maven項目時首先會從本地倉庫查找資源,如果沒有那么Maven會從遠(yuǎn)程倉庫下載到你本地倉庫,這篇文章主要給大家介紹了關(guān)于maven安裝、使用、配置本地倉庫、idea配置maven以及解決plugins報錯問題的相關(guān)資料,需要的朋友可以參考下2024-01-01springboot serverEndpoint導(dǎo)致@resource注解不生效
在SpringBoot中,@Resource注解用于注入依賴,本文主要介紹了springboot serverEndpoint導(dǎo)致@resource注解不生效,具有一定的參考價值,感興趣的可以了解一下2023-12-12redis發(fā)布訂閱Java代碼實現(xiàn)過程解析
這篇文章主要介紹了redis發(fā)布訂閱Java代碼實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09java控制臺實現(xiàn)學(xué)生信息管理系統(tǒng)(集合版)
這篇文章主要為大家詳細(xì)介紹了java控制臺實現(xiàn)學(xué)生信息管理系統(tǒng)的集合版,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04SpringBoot引入Thymeleaf的實現(xiàn)方法
這篇文章主要介紹了SpringBoot引入Thymeleaf的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04