Public field automatic filling in Mybatis Plus
This article mainly introduces the relevant information of SpringBoot Mybatis Plus public field automatic filling function. Friends who need it can refer to it
1. Application scenarios
Usually when building an object table, there will be two fields: last modification time and last modification person. For these fields that most tables have, these must be taken into consideration every time when adding or modifying. It's very troublesome to know whether several fields have been passed in. mybatisPlus has a great solution. That is the function of automatic filling of public fields. Generally, this function can be used for fields that meet the following conditions:
This field is found in most tables.
The value of this field is fixed, or the field value can be obtained dynamically in the background.
The two fields commonly used are last_update_time and last_update_name.
2. Configure MybatisPlus
Guide package: The only thing to note is that mybatisPlus is only supported in version 2.0.6Update Data public fields are automatically filled in. Previously, they could only be used when adding new data.
If you are a student who has configured MybatisPlus before, you only need to add the following steps:
Inherit IMetaObjectHandlerAbstract class, implement insertFill() new There are two methods: field settings that need to be filled when adding data and field settings that need to be filled when updateFill() updates data:
package io.z77z.util; import java.util.Date; import org.apache.ibatis.reflection.MetaObject; import org.apache.shiro.SecurityUtils; import org.springframework.stereotype.Component; import com.baomidou.mybatisplus.mapper.MetaObjectHandler; import io.z77z.entity.SysUser; /** mybatisplus自定义填充公共字段 ,即没有传的字段自动填充*/ @Component public class MyMetaObjectHandler extends MetaObjectHandler { //新增填充 @Override public void insertFill(MetaObject metaObject) { Object lastUpdateNameId = metaObject.getValue("lastUpdateNameId"); Object lastUpdateTime = metaObject.getValue("lastUpdateTime"); //获取当前登录用户 SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal(); if (null == lastUpdateNameId) { metaObject.setValue("lastUpdateNameId", user.getId()); } if (null == lastUpdateTime) { metaObject.setValue("lastUpdateTime", new Date()); } } //更新填充 @Override public void updateFill(MetaObject metaObject) { insertFill(metaObject); } }
Note: The parameters of the getValue() method are variables in the pojo class (Camel case naming method).
In the configuration file of mybatisplus, the bean of the public field generation class:
// MP 全局配置,更多内容进入类看注释 GlobalConfiguration globalConfig = new GlobalConfiguration(); //配置公共字段自动填写 globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
is the setting to fill in the public field just written to the MP global configuration object.
Filled fields need to ignore validation, add the following annotation on the corresponding attribute of the table object pojo class:
/** * 最后修改人Id */ @TableField(value="last_update_id",validate=FieldStrategy.NOT_EMPTY) private String lastUpdateNameId; /** * 最后修改时间 */ @TableField(value="last_update_time",validate=FieldStrategy.NOT_EMPTY) private Date lastUpdateTime;
Reason: Because when the update and insert methods are called, It will verify whether the attribute you passed is empty to determine whether this attribute should be updated and inserted. This conflicts with the automatic filling of public fields, so this annotation is needed to identify that this attribute does not require verification. Otherwise, the filling will fail during insertion.
3. Writing test classes
//公共字段自动填充 //1.在mybatisplus的配置文件中公共字段生成类的bean //2.实现IMetaObjectHandler类 //3.忽略对应字段的为空检测,在pojo类的属性上添加@TableField(value="last_update_name_id",validate=FieldStrategy.IGNORED) @Test public void publicTest(){ SysUser user = new SysUser(); user.setEmail("1093615728@qq.com"); user.setNickname("z77z"); user.setPswd("123123"); user.setStatus("1"); sysUserService.insert(user); sysUserService.selectById(user.getId()); SysUser user1 = new SysUser(); user1.setPswd("123"); user1.setId(user.getId()); sysUserService.updateById(user1); sysUserService.selectById(user.getId()); }
4. Test log
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.insert- ==> Preparing: INSERT INTO sys_user (id, nickname, email, pswd, `status`,last_update_name_id , last_update_time ) VALUES ( ?, ?, ?, ?, ?,?, ? )
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.insert- ==> ; Parameters: 6634923de4a14b6ca3bac5fdf31563a8(String), z77z(String), 1093615728@qq.com(String), 123123(String), 1(String), 123(String), 2017-04-23 19:35:26.58(Time stamp)
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.insert- <== Updates: 1
2017/04/23-19:35:26 [ main] DEBUG io.z77z.dao.SysUserMapper.selectById- ==> createTime FROM sys_user WHERE id=?
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- ==> Parameters: 6634923de4a14b6ca3bac5fdf31563a8(String)
2017/ 04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- <== Total: 1
2017/04/23-19:35:26 [main] DEBUG io. z77z.dao.SysUserMapper.updateById- ==> Preparing: UPDATE sys_user SET pswd=?, last_update_name_id=?, last_update_time=? WHERE id=?
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.updateById- ==> /04 /23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.updateById- <== Updates: 1
2017/04/23-19:35:26 [main] DEBUG io.z77z .dao.SysUserMapper.selectById- ==> Preparing: SELECT id,nickname,email,pswd,last_login_time AS lastLoginTime,`status`,last_update_name_id AS lastUpdateNameId,create_name_id AS createNameId,last_update_time AS lastUpdateTime,create_time AS createTime FROM sys_user WHERE id= ?
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- ==> Parameters: 6634923de4a14b6ca3bac5fdf31563a8(String)
2017/04/23-19: 35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- <== Total: 1
##5. Summary It was originally planned to use this method to process the creator and creation time. Finally, it was found that if these two fields are also ignored as empty, that is, validate=FieldStrategy.NOT_EMPTY is added when updating the data. The creator and creation time will be updated together. Otherwise, it will be updated to empty. So I think the public field autofill function of mybatisPlus is good, but it is not perfect when used for real needs. 【Related recommendations】
The above is the detailed content of Public field automatic filling in Mybatis Plus. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Detailed explanation of MyBatis caching mechanism: One article to understand the principle of cache storage Introduction When using MyBatis for database access, caching is a very important mechanism, which can effectively reduce access to the database and improve system performance. This article will introduce the caching mechanism of MyBatis in detail, including cache classification, storage principles and specific code examples. 1. Cache classification MyBatis cache is mainly divided into two types: first-level cache and second-level cache. The first-level cache is a SqlSession-level cache. When

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

As network technology continues to develop, database attacks are becoming more and more common. SQL injection is one of the common attack methods. Attackers enter malicious SQL statements into the input box to perform illegal operations, causing data leakage, tampering or even deletion. In order to prevent SQL injection attacks, developers must pay special attention when writing code, and when using an ORM framework such as MyBatis, they need to follow some best practices to ensure the security of the system. 1. Parameterized query Parameterized query is the anti-
