当前位置:网站首页>Automatic filling of database public fields
Automatic filling of database public fields
2022-07-04 13:51:00 【YXXYX】
introduction
Database tables of many projects will be set create_time、update_time Other public fields , These public fields need to be set when the database is created or updated ; If you set it yourself, you need to write extra set Code , Once there are many such watches, it will be troublesome ; So we can find a way to make these fields automatically filled ; and mybatis-plus It just provides such a function ;
mysql You can set the default value of the field CURRENT_TIMESTAMP Add the current time every time you insert data , Update can be set on update CURRENT_TIMESTAMP Implement the update operation to update the time :
But I don't particularly recommend this method , If you let the database complete these logical operations, the responsibility is not clear , And it is not conducive to others to understand from the code ;
Here's how to use mybatis-plus Realize the automatic filling of public fields
Code operation
First you need to create a population data processor , Realization MetaObjectHandler:
/** * mybatis-plus Automatic attribute filling function provided */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
// Insert data auto fill
@Override
public void insertFill(MetaObject metaObject) {
log.info(" New data is automatically filled ...");
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
}
// Update data auto fill
@Override
public void updateFill(MetaObject metaObject) {
log.info(" Update data auto fill ...");
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
}
}
The processor needs to be handed over to Sping management , add @Component annotation ;
Sometimes there will be createUser What fields , Add flexibly :

After this step is completed , Next, just add @TableField annotation :
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
Mainly @TableField Annotated fill attribute :
- INSERT Fill in when inserting
- UPDATE Fill in on update
- INSERT_UPDATE Both update and insert are populated
- DEFAULT By default , Nothing is filled

In this way, the automatic filling is set , You can test :
The new data

Update data

In the database create_time and update_time They also have corresponding values :

In this way, the overall automatic filling operation, that is, configuration, is completed ;
Step on the pit diary : Automatic filling principle
There is a problem in writing this project : update operation update Auto fill does not take effect when ;
After investigation, it is found that the updated data comes from the front end update_time Field Already exist A time value ( I found this value from the database );
So I guess If the field to be automatically filled already has a value , Then the automatic filling mechanism will no longer fill the field with values ;
Because auto fill takes effect and strictUpdateFill() Methods matter ( Take update as an example ), So I debug Check its source code :
First of all, no matter whether there is a value in the automatic filling, it will enter the method :

Then enter the method :

Then through a round-trip call ( You can try it yourself , Don't show if it's not important ), Came to the following method :

This method can show the strategy of automatic filling : Only when the public fill field is empty, it will be automatically filled ; Briefly explain the key code :
- fieldName: Public fill field name
- fieldVal: Generated public fill field values
if (metaObject.getValue(fieldName) == null) {
// Judge whether the value of the public fill field is empty , If it is empty, it will be filled automatically , Not empty, end directly
Object obj = fieldVal.get(); // Get the automatically generated fill value
if (Objects.nonNull(obj)) {
// Judge whether the filling value is empty
metaObject.setValue(fieldName, obj); // Assign the filling value to this field , Realize the automatic filling of public fields
}
}
Of course, there are still some steps to follow , Here is just a list of the key steps ;
Then I put update_time The field is manually assigned a null value before being passed to the backend , Auto fill takes effect ;
summary
in general , Automatic filling of public fields is still very easy to use , Save a lot of code ; Of course, one thing to keep in mind : Make sure that the fields that need to be automatically filled are empty , Only in this way can the automatic filling mechanism take effect
Personal records , If you have any questions, please contact us !
边栏推荐
- Annual comprehensive analysis of China's mobile reading market in 2022
- Besides, rsync+inotify realizes real-time backup of data
- C语言图书租赁管理系统
- Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
- Scrapy 框架学习
- 2022年山东省安全员C证考试题库及在线模拟考试
- 2022年起重机械指挥考试模拟100题模拟考试平台操作
- 30:第三章:开发通行证服务:13:开发【更改/完善用户信息,接口】;(使用***BO类承接参数,并使用了参数校验)
- remount of the / superblock failed: Permission denied
- C语言个人通讯录管理系统
猜你喜欢

7 月数据库排行榜:MongoDB 和 Oracle 分数下降最多

CommVault cooperates with Oracle to provide metallic data management as a service on Oracle cloud
![[AI system frontier dynamics, issue 40] Hinton: my deep learning career and research mind method; Google refutes rumors and gives up tensorflow; The apotheosis framework is officially open source](/img/2c/b1d6277c1b23a6a77f90d5b2874759.png)
[AI system frontier dynamics, issue 40] Hinton: my deep learning career and research mind method; Google refutes rumors and gives up tensorflow; The apotheosis framework is officially open source

MySQL 45 lecture - learn the actual combat notes of MySQL in Geek time 45 lecture - 06 | global lock and table lock_ Why are there so many obstacles in adding a field to the table

JVM series - stack and heap, method area day1-2

室外LED屏幕防水吗?

免费、好用、强大的轻量级笔记软件评测:Drafts、Apple 备忘录、Flomo、Keep、FlowUs、Agenda、SideNote、Workflowy

爬虫练习题(一)

It is six orders of magnitude faster than the quantum chemical method. An adiabatic artificial neural network method based on adiabatic state can accelerate the simulation of dual nitrogen benzene der

聊聊支付流程的设计与实现逻辑
随机推荐
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
数据库公共字段自动填充
SQL language
一次 Keepalived 高可用的事故,让我重学了一遍它
基于STM32+华为云IOT设计的酒驾监控系统
Runc hang causes the kubernetes node notready
Source code compilation and installation of MySQL
面试官:Redis中哈希数据类型的内部实现方式是什么?
unity不识别rider的其中一种解决方法
Scrapy 框架学习
担心“断气” 德国正修改《能源安全法》
C语言个人通讯录管理系统
聊聊支付流程的设计与实现逻辑
Go 语言入门很简单:Go 实现凯撒密码
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
It is six orders of magnitude faster than the quantum chemical method. An adiabatic artificial neural network method based on adiabatic state can accelerate the simulation of dual nitrogen benzene der
2022G3锅炉水处理考试题模拟考试题库及模拟考试
Solution: how to delete the information of Jack in two tables with delete in one statement in Oracle
Optional values and functions of the itemized contenttype parameter in the request header
安装trinity、解决报错
