Mybatis-Plus实现字段的自动填充

给字段加注解

@ApiModelProperty(value = "创建人")
@TableField(fill = FieldFill.INSERT)
private String createBy;

@ApiModelProperty(value = "修改人")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;

实现MetaObjectHandler

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hrwms.common.base.UserEntity;
import com.hrwms.common.utils.UserContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class FillHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        String userName = UserContext.currentUserOpt().map(UserEntity::getUserName).orElse("sys");
        this.setFieldValByName("createBy", userName,metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userName = UserContext.currentUserOpt().map(UserEntity::getUserName).orElse("sys");
        this.setFieldValByName("updateBy", userName,metaObject);
    }
}

将创建的FillHandler类注入到配置中(重要)

如果项目中使用配置类创建了SqlSessionFactory,需要手动将自定义的MetaObjectHandler注入

@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
    //获取mybatis-plus全局配置
    GlobalConfig globalConfig = GlobalConfigUtils.defaults();
    //mybatis-plus全局配置设置元数据对象处理器为自己实现的那个
    globalConfig.setMetaObjectHandler(new FillHandler());
    mybatisSqlSessionFactoryBean.setDataSource(dataSource);
    //mybatisSqlSessionFactoryBean关联设置全局配置
    mybatisSqlSessionFactoryBean.setGlobalConfig(globalConfig);
    return mybatisSqlSessionFactoryBean.getObject();
}

说明:一般在updateById、save和saveBatch api才生效

参考文章1
参考文章2

posted @ 2024-08-08 15:49  品书读茶  阅读(48)  评论(0编辑  收藏  举报