mybatis-plus 配置时间字段自动填充

mybatis-plus 配置时间字段自动填充

MyBatis-Plus 提供了自动填充(AutoFill)功能,可以在插入或者更新数据时自动填充某些字段,比如创建时间和更新时间。

首先要在表中定义一个创建时间和更新时间的字段,通常我们使用 DATETIME 类型。

然后在实体类中定义这两个属性,使用 @TableField 注解来指定属性和表中字段的映射关系,并且使用 @TableLogic 注解来标示逻辑删除字段(如果有需要):

public class User {
    
    @TableId
    private Long id;
    
    private String name;
    
    @TableField(fill = FieldFill.INSERT) // 创建时间在插入时自动填充
    private LocalDateTime createTime;
    
    @TableField(fill = FieldFill.UPDATE) // 更新时间在更新时自动填充
    private LocalDateTime updateTime;
    
    @TableLogic // 标记逻辑删除字段
    private Integer deleted;
    
    // setter/getter 省略  
}

 

接着,需要配置自动填充处理器(MetaObjectHandler),可以在其中指定某些列的填充值。比如我们可以在插入时自动填充创建时间,更新时间,更新人(根据实际情况可以只填充一部分):

@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MyMetaObjectHandler();
    }
}

public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "createUser", Long.class, CurrentUser.id()); // 也可以填充其他属性
    }
    
    // 更新时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}

 

注入自定义的 MetaObjectHandler 之后,当执行插入或更新操作时,自动填充处理器会自动为指定的列填充值。

最后别忘了在应用程序启动时执行 MybatisPlusConfig 这个类中的 bean 创建过程。

本站为非盈利性站点,所有资源、文章等仅供学习参考,并不贩卖软件且不存在任何商业目的及用途,如果您访问和下载某文件,表示您同意只将此文件用于参考、学习而非其他用途。
本站所发布的一切软件资源、文章内容、页面内容可能整理来自于互联网,在此郑重声明本站仅限用于学习和研究目的;并告知用户不得将上述内容用于商业或者非法用途,否则一切后果请用户自负。
如果本站相关内容有侵犯到您的合法权益,请仔细阅读本站公布的投诉指引页相关内容联系我,依法依规进行处理!
作者:理想
链接:https://www.imyjs.cn/archives/shuoshuo/mybatis-plus-%e9%85%8d%e7%bd%ae%e6%97%b6%e9%97%b4%e5%ad%97%e6%ae%b5%e8%87%aa%e5%8a%a8%e5%a1%ab%e5%85%85
THE END
二维码
mybatis-plus 配置时间字段自动填充
mybatis-plus 配置时间字段自动填充 MyBatis-Plus ……
<<上一篇
下一篇>>