官网文档
https://mybatis.plus/guide/auto-fill-metainfo.html
对象添加注解
@TableField(fill = FieldFill.INSERT_UPDATE)
public enum FieldFill {
/**
* 默认不处理
*/
DEFAULT,
/**
* 插入填充字段
*/
INSERT,
/**
* 更新填充字段
*/
UPDATE,
/**
* 插入和更新填充字段
*/
INSERT_UPDATE
}
@Data
@TableName("discovery_page_config")
public class DiscoveryPageConfig implements Serializable {
private static final long serialVersionUID = -1L;
/**
* 操作人id
*/
@ApiModelProperty(value = "操作人id")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long operatorId;
}
自定义实现类 MyMetaObjectHandler
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
if (metaObject.hasSetter("operatorId")) {
//添加默认的操作者
this.setFieldValByName("operatorId", JwtUtil.getUserId(), metaObject);
}
}
@Override
public void updateFill(MetaObject metaObject) {
if (metaObject.hasSetter("operatorId")) {
this.setFieldValByName("operatorId", JwtUtil.getUserId(), metaObject);
}
}
}
配置填充处理器
@Bean(name = "masterSqlSessionFactory")
@Primary
public MybatisSqlSessionFactoryBean masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource){
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(masterDataSource);
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
mybatisPlus.setGlobalConfig(globalConfig);
return mybatisPlus;
}
评论区