MyBatis-Plus字段自动填充功能

第一章、插入数据库字段时通常需要带上创建时间

①在设计数据库表时,通常必须有以下字段,而MyBatis-Plus提供字段填充功能可以让我们轻松实现插入数据的同时,在createTime字段或者updatedTime填充当前时间。

自增ID
创建时间:createdTime
修改时间:updatedTime
创建人:createBy
修改人:updateBy

②确保数据库时间字段类型与实体类中的字段类型匹配
如:实体类中的字段类型为java.util.Date
则数据库的字段为TIMESTAMP

③在application.yaml文件中配置下面这些信息,允许bean定义重写,其实不配置也行,就当拓展知识点了。

spring:
  main:
    allow-bean-definition-overriding: true

第二章、配置MetaObjectHandler类开启自动填充功能

①创建一个类并实现MetaObjectHandler接口,该接口包含了insertFill和updateFill两个方法,用于指定在插入和更新操作时自动填充的字段

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdTime", Date.class, new Date());
        // 其他需要插入填充的字段
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedTime", Date.class, new Date());
        // 其他需要更新填充的字段
    }
}

第三章、字段上使用@TableField

实体类的相应字段上使用@TableField注解,指定需要自动填充的字段。

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("table_user")
public class user{
    @TableId(type = IdType.AUTO)
    private Long id;

    @TableField(value = "created_time",fill = FieldFill.INSERT)
    private Date createdTime;

    @TableField(value = "updated_time",fill = FieldFill.INSERT_UPDATE)
    private Date updatedTime;

    // 其他字段
}

配置好以后,尝试插入数据,发现插入数据的同时created_time字段已经填充了当前时间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值