当前位置:网站首页>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 !
边栏推荐
- Database lock table? Don't panic, this article teaches you how to solve it
- Xilinx/system-controller-c/boardui/ unable to connect to the development board, the solution of jamming after arbitrary operation
- Comprehensive evaluation of modular note taking software: craft, notation, flowus
- Alibaba cloud award winning experience: build a highly available system with polardb-x
- 使用宝塔部署halo博客
- 舔狗舔到最后一无所有(状态机)
- AI painting minimalist tutorial
- unity不识别rider的其中一种解决方法
- Introduction to reverse debugging PE structure resource table 07/07
- C语言集合运算
猜你喜欢

CA: efficient coordinate attention mechanism for mobile terminals | CVPR 2021

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

The only core indicator of high-quality software architecture

Go 语言入门很简单:Go 实现凯撒密码

DGraph: 大规模动态图数据集

Oracle 被 Ventana Research 评为数字创新奖总冠军

Personalized online cloud database hybrid optimization system | SIGMOD 2022 selected papers interpretation

Redis —— How To Install Redis And Configuration(如何快速在 Ubuntu18.04 与 CentOS7.6 Linux 系统上安装 Redis)

2022年起重机械指挥考试模拟100题模拟考试平台操作

CANN算子:利用迭代器高效实现Tensor数据切割分块处理
随机推荐
一个数据人对领域模型理解与深入
Animation and transition effects
C語言宿舍管理查詢軟件
Source code compilation and installation of MySQL
. Net delay queue
Efficient! Build FTP working environment with virtual users
Getting started with the go language is simple: go implements the Caesar password
Getting started with microservices
C语言职工管理系统
OpenHarmony应用开发之如何创建DAYU200预览器
Comprehensive evaluation of modular note taking software: craft, notation, flowus
WS2811 M是三通道LED驱动控制专用电路彩灯带方案开发
Scripy framework learning
Distributed base theory
C语言中学生成绩管理系统
The old-fashioned synchronized lock optimization will make it clear to you at once!
CommVault cooperates with Oracle to provide metallic data management as a service on Oracle cloud
Introduction to XML III
Introduction to XML I
Redis - how to install redis and configuration (how to quickly install redis on ubuntu18.04 and centos7.6 Linux systems)
