当前位置:网站首页>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 !
边栏推荐
- Xilinx/system-controller-c/boardui/ unable to connect to the development board, the solution of jamming after arbitrary operation
- After the game starts, you will be prompted to install HMS core. Click Cancel, and you will not be prompted to install HMS core again (initialization failure returns 907135003)
- E-week finance | Q1 the number of active people in the insurance industry was 86.8867 million, and the licenses of 19 Payment institutions were cancelled
- Three schemes to improve the efficiency of MySQL deep paging query
- Go zero micro service practical series (IX. ultimate optimization of seckill performance)
- FS4056 800mA充电ic 国产快充电源ic
- Openharmony application development how to create dayu200 previewer
- 8 expansion sub packages! Recbole launches 2.0!
- 数据库公共字段自动填充
- "Tips" to slim down Seurat objects
猜你喜欢

DGraph: 大规模动态图数据集

免费、好用、强大的轻量级笔记软件评测:Drafts、Apple 备忘录、Flomo、Keep、FlowUs、Agenda、SideNote、Workflowy
提高MySQL深分页查询效率的三种方案

博士申请 | 西湖大学学习与推理系统实验室招收博后/博士/研究实习等
![[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

三星量产3纳米产品引台媒关注:能否短期提高投入产出率是与台积电竞争关键

高质量软件架构的唯一核心指标

室外LED屏幕防水吗?

2022G3锅炉水处理考试题模拟考试题库及模拟考试
高效!用虚拟用户搭建FTP工作环境
随机推荐
Redis - how to install redis and configuration (how to quickly install redis on ubuntu18.04 and centos7.6 Linux systems)
MySQL three-level distribution agent relationship storage
爬虫练习题(一)
易周金融 | Q1保险行业活跃人数8688.67万人 19家支付机构牌照被注销
Annual comprehensive analysis of China's mobile reading market in 2022
Dgraph: large scale dynamic graph dataset
程序员转方向
免费、好用、强大的轻量级笔记软件评测:Drafts、Apple 备忘录、Flomo、Keep、FlowUs、Agenda、SideNote、Workflowy
c#数组补充
C#基础补充
Cors: standard scheme of cross domain resource request
Introduction to XML III
三星量产3纳米产品引台媒关注:能否短期提高投入产出率是与台积电竞争关键
.Net之延迟队列
微服务入门
担心“断气” 德国正修改《能源安全法》
C#基础深入学习二
Introduction to reverse debugging PE structure resource table 07/07
2022年起重机械指挥考试模拟100题模拟考试平台操作
Xue Jing, director of insight technology solutions: Federal learning helps secure the flow of data elements
