In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to use Java MyBatis interceptor to improve work efficiency, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Scene:
In the development of back-end services, the popular framework combination is SSM (SpringBoot + Spring + MyBatis). When we develop some business systems, there will be a lot of business data tables, and the information in the tables will be re-inserted, and many operations may be carried out in the whole life cycle.
For example, when we buy an item on a website, we will generate an order record, and the order status will become paid after the amount has been paid, and when we finally receive the order goods, the order status will become completed, etc.
Suppose the t_order result of our order table is as follows:
When the order is created, you need to set the value of insert_by,insert_time,update_by,update_time
When you update the status of the order, you only need to update the value of update_by,update_time.
How should we deal with it?
1. Muggle practice
The simplest approach, and the easiest to think of, is to process the relevant fields in the code that each business processes.
For example, in the method of order creation, the process is as follows:
Public void create (Order order) {/ /... Other code / / sets audit fields Date now = new Date (); order.setInsertBy (appContext.getUser ()); order.setUpdateBy (appContext.getUser ()); order.setInsertTime (now); order.setUpdateTime (now); orderDao.insert (order);}
The order update method only sets updateBy and updateTime:
Public void update (Order order) {/ /... Other code / / set audit field Date now = new Date (); order.setUpdateBy (appContext.getUser ()); order.setUpdateTime (now); orderDao.insert (order);}
Although this approach can complete the function, there are some problems:
You need to decide which fields to set according to different business logic in each method.
After the business model becomes more, it is set in the business method of each model, and there is too much code repetition.
Well, after we know that there is a problem with this way, we have to find out if there is a good way to do it. Look down!
two。 Elegant approach
Because our persistence layer framework uses MyBatis more, we use MyBatis's interceptor to complete our function.
First of all, let's find out, what is an interceptor?
3. What is an interceptor?
MyBatis's interceptor, as its name implies, is to intercept certain operations. The interceptor can intercept some methods before and after execution and add some processing logic.
MyBatis's interceptor can intercept the Executor, StatementHandler, PameterHandler, and ResultSetHandler interfaces, that is, proxying these four objects.
The original purpose of the interceptor is to let users do not have to modify the source code of MyBatis in the processing flow of MyBatis, and can be integrated into the whole execution process in the way of plug-in.
For example, Executor in MyBatis includes BatchExecutor, ReuseExecutor, SimpleExecutor and CachingExecutor. If none of these query methods can meet your needs, we can intercept the query method of the Executor interface by building an interceptor instead of directly modifying the source code of MyBatis. After intercepting, we can implement our own query method logic.
Interceptors in MyBatis are represented by the Interceptor interface, which has three methods.
Public interface Interceptor {Object intercept (Invocation invocation) throws Throwable; Object plugin (Object target); void setProperties (Properties properties);}
The plugin method is used by the interceptor to encapsulate the target object, through which we can return either the target object itself or one of its proxies.
When a proxy is returned, we can intercept the methods in it to call the intercept method, and of course we can call other methods.
The setProperties method is used to specify some properties in the Mybatis configuration file.
4. Update audit fields using interceptor
So how should we implement our function of assigning values to audit fields through interceptors?
When we create and modify an order, we essentially execute insert and update statements through MyBatis, and MyBatis is processed through Executor.
We can intercept Executor through the interceptor, and then set insert_by,insert_time,update_by,update_time and other attribute values for the data object to be inserted in the interceptor according to the statement executed.
5. Custom interceptor
The most important thing about customizing Interceptor is to implement the plugin method and the intercept method.
In the plugin method, we can decide whether to intercept and then decide what kind of target object to return.
The intercept method is the method to be executed when you want to intercept.
As far as the plugin method is concerned, Mybatis already provides us with an implementation. There is a class called Plugin in Mybatis with a static method wrap (Object target,Interceptor interceptor) that allows you to determine whether the object to be returned is the target object or the corresponding proxy.
But there is also a problem here, that is, how do we know in the interceptor that the table to be inserted has audit fields to deal with?
Because not all of our tables are business tables, there may be some dictionary tables or definition tables that do not have audit fields, which we do not need to deal with in the interceptor.
In other words, we need to be able to distinguish which objects need to update the audit field.
Here we can define an interface that can be implemented uniformly by all models that need to update audit fields, and this interface acts as a tag.
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}
Next, we can implement our custom interceptor.
@ 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 {/ / get the user name String userName = AppContext.getUser () from the context; Object [] args = invocation.getArgs () SqlCommandType sqlCommandType = null; for (Object object: args) {/ / get the operation type if (object instanceof MappedStatement) {MappedStatement ms = (MappedStatement) object; sqlCommandType = ms.getSqlCommandType () from the MappedStatement parameter; logger.debug ("Action Type: {}", sqlCommandType); continue } / / determine whether the parameter is of BaseDO type / / A parameter 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 compatible updateByExampleSelective (record, example) If (object instanceof ParamMap) {logger.debug ("mybatis arg: {}", object); @ SuppressWarnings ("unchecked") ParamMap parasMap = (ParamMap) 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;} / / compatible bulk insert if (object instanceof DefaultSqlSession.StrictMap) {logger.debug ("mybatis arg: {}", object) @ SuppressWarnings ("unchecked") DefaultSqlSession.StrictMap map = (DefaultSqlSession.StrictMap) object; String key = "collection"; if (! map.containsKey (key)) {continue;} ArrayList 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) {}}
As you can see from the above code, our custom interceptor IbatisAuditDataInterceptor implements the Interceptor interface.
In the @ Intercepts annotation on our interceptor, the type parameter specifies that the intercepted class is the implementation of the Executor interface, and the method parameter specifies to intercept the update method in the Executor, because the addition, deletion and modification of database operations are performed through the update method.
6. Configure the interceptor plug-in
After the interceptor is defined, the interceptor needs to be specified in the plugins of the SqlSessionFactoryBean to take effect. So configure it as follows.
Classpath:META-INF/mapper/*.xml
At this point, our custom interceptor takes effect. Through the test, you will find that instead of manually setting the value of the audit field in the business code, the audit field will be automatically assigned through the interceptor plug-in after the transaction is committed.
The above is all the content of the article "how to use Java MyBatis interceptor to improve productivity". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.