当前位置:网站首页>数据库公共字段自动填充
数据库公共字段自动填充
2022-07-04 12:44:00 【YXXYX】
引言
很多项目的数据库表都会设置create_time、update_time等公共字段,这些公共字段都是在数据库创建或更新时需要设置值;如果自己设置还需要额外写set代码,一旦这样的表多了之后就很麻烦;所以我们可以想办法让这些字段可以自动填充;而mybatis-plus正好提供了这样的功能;
mysql中可以通过设置字段默认值CURRENT_TIMESTAMP实现每次插入数据添加当前时间,更新可以设置on update CURRENT_TIMESTAMP实现更新操作更新该时间:
但是我并不是特别推荐这种方法,如果让数据库完成这些逻辑操作职责就不太明确,并且不利于他人从代码中理解;
下面演示一下如何使用mybatis-plus实现公共字段自动填充
代码操作
首先需要创建一个填充数据处理器,实现MetaObjectHandler:
/** * mybatis-plus提供的属性自动填充功能 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入数据自动填充
@Override
public void insertFill(MetaObject metaObject) {
log.info("新增数据自动填充...");
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
}
// 更新数据自动填充
@Override
public void updateFill(MetaObject metaObject) {
log.info("更新数据自动填充...");
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
}
}
该处理器需要交给Sping管理,加上@Component注解;
有时会有createUser什么的字段,灵活添加即可:
这一步完成后,接下来只需要在公共填充的字段上加上 @TableField 注解:
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
主要就是@TableField注解的fill属性:
- INSERT插入时填充
- UPDATE更新时填充
- INSERT_UPDATE更新和插入时都填充
- DEFAULT默认情况,什么都不填充
这样自动填充就设置好了,可以测试一下:
新增数据
更新数据
数据库中create_time和update_time也都有了对应值:
这样整体的自动填充操作即配置就完成了;
踩坑日记:自动填充原理
这次写项目中遇到了一个问题:更新操作update时自动填充没有生效;
经过排查发现前端传来更新的数据时update_time字段已经存在一个时间值(这个值是我从数据库中查出来的);
所以我猜测如果需要自动填充的字段已经存在值的话,那么自动填充机制就不会再给该字段填充值;
因为自动填充生效和strictUpdateFill()方法有关系(以更新为例),所以就debug了一下它的源码:
首先不论填充自动是否存在数值都会进入该方法:
然后进入该方法:
然后通过了一番来回调用(可以自己尝试看看,不重要就不展示了),来到了如下方法:
这个方法就可以看出来自动填充的策略了:只有公共填充字段为空时才会自动填充;简单解释一下关键代码:
- fieldName:公共填充字段名
- fieldVal:生成的公共填充字段值
if (metaObject.getValue(fieldName) == null) {
// 判断公共填充字段的值是否为空,如果为空才自动填充,不为空直接结束
Object obj = fieldVal.get(); // 获取自动生成的填充值
if (Objects.nonNull(obj)) {
// 判断填充值是否为空
metaObject.setValue(fieldName, obj); // 将填充值赋给该字段,实现了公共字段自动填充
}
}
当然后面还有一些步骤,这里只是把关键一步列了出来;
然后我在前端把update_time字段传给后端之前手动赋了空值,自动填充就生效了;
总结
总的来说,公共字段自动填充还是很好用的,省去很多代码;当然需要牢记一点:一定要保证需要自动填充的字段为空,这样自动填充机制才生效
个人记录,如果有问题欢迎交流!
边栏推荐
- 光环效应——谁说头上有光的就算英雄
- Interviewer: what is the difference between redis expiration deletion strategy and memory obsolescence strategy?
- Efficient! Build FTP working environment with virtual users
- C语言宿舍管理查询软件
- C#/VB. Net to add text / image watermarks to PDF documents
- Besides, rsync+inotify realizes real-time backup of data
- N++ is not reliable
- C#基础补充
- A data person understands and deepens the domain model
- WPF double slider control and forced capture of mouse event focus
猜你喜欢
CVPR 2022 | transfusion: Lidar camera fusion for 3D target detection with transformer
Database lock table? Don't panic, this article teaches you how to solve it
高效!用虚拟用户搭建FTP工作环境
光环效应——谁说头上有光的就算英雄
室外LED屏幕防水吗?
Is the outdoor LED screen waterproof?
Valentine's Day confession code
8个扩展子包!RecBole推出2.0!
"Pre training weekly" issue 52: shielding visual pre training and goal-oriented dialogue
Master the use of auto analyze in data warehouse
随机推荐
The old-fashioned synchronized lock optimization will make it clear to you at once!
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
Dry goods sorting! How about the development trend of ERP in the manufacturing industry? It's enough to read this article
【云原生 | Kubernetes篇】深入了解Ingress(十二)
Personalized online cloud database hybrid optimization system | SIGMOD 2022 selected papers interpretation
8个扩展子包!RecBole推出2.0!
2022年中国移动阅读市场年度综合分析
Using scrcpy projection
Comparative study of the gods in the twilight Era
诸神黄昏时代的对比学习
用fail2ban阻止密码尝试攻
Backgroundworker usage example
提高MySQL深分页查询效率的三种方案
高效!用虚拟用户搭建FTP工作环境
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
A data person understands and deepens the domain model
ASP.NET Core入门一
Meituan Ali's Application Practice on multimodal recall
7 月数据库排行榜:MongoDB 和 Oracle 分数下降最多
Alibaba cloud award winning experience: build a highly available system with polardb-x