mybatis自动填充多个表相同字段的值

有很多表的设计里面,有一些字段都是相同的,类似
createTime,updateTime等等,这些字段如果每次在插入或更新时都操作一次很烦锁,
mybatis提供了机制可以很方便的自动填充这些字段
具体做法

1.在字段上添加注解

//插入时填充
@TableField(fill = FieldFill.INSERT)
    private Date createTime;

//更新时填充
@TableField(fill = FieldFill.UPDATE)
    private Date updateTime;

2.新建 MetaObjectHandler实现类
这里结合springboot-security可以获得当前的登录用户

public class MyBatisMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SystemUser cusotmUser = (SystemUser) authentication.getPrincipal();
        this.strictInsertFill(metaObject,"createTime", Date.class,new Date());
        this.strictInsertFill(metaObject,"createUserId",String.class,cusotmUser.getUserId());
        this.strictInsertFill(metaObject,"createUserName",String.class,cusotmUser.getUserName());
        
    }
    
    @Override
    public void updateFill(MetaObject metaObject) {
        //更新要判空,有这样的场景,用户输入错误的密码需要更新输错的次数,这个时候用户还没有登录
        //一个折中方案,当用户未登录时userId默认为admin用户的id
        String userId = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null){
            SystemUser cusotmUser = (SystemUser) authentication.getPrincipal();
            userId = cusotmUser.getUserId();
        }
        
        
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateUserId",userId,metaObject);
    }
}

3.配置 MetaObjectHandler

    //自动填充配置
    @Bean
    public MetaObjectHandler myMetaObjectHandler() {
        return new MyBatisMetaObjectHandler();
    }

    //分页配置
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

这样在插入和更新的时候,这些字段会自动被填充

posted @ 2024-05-03 03:06  猝死的路上  阅读(84)  评论(0编辑  收藏  举报