解决的问题:
日常开发中数据表往往会有几个公共字段,例如create_by,update_by,ceate_time,update_time. 当我们每次需要添加或者更新数据的时候 都需要联带的去更新公共字段, 那么每次都在做着重复的操作, 所以可以利用mybatis的着色器插件在进行数据操作的时候进行自动赋值公共字段的操作, 可以减少每次繁琐且枯燥的字段填充操作
进行mybatis着色器配置
@Configuration
public class MybatisPlusConfig {
@Autowired
ApplicationContext applicationContext;
@Bean
public GlobalConfig customerMetaObjectHandler() {
//获取spring-mybatis默认的会话工厂
SqlSessionFactory bean = applicationContext.getBean(SqlSessionFactory.class);
//全局配置
GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(bean.getConfiguration());
//配置填充器
globalConfig.setMetaObjectHandler(new CustomerMetaObjectHandler());
return globalConfig;
}
}
自定义公共字段类
@Data
public class AuditFields {
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
private Long createdBy;
/**
* 更新人
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateBy;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
自定义着色器handler
public class CustomerMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
// 这里使用了SpringSecurity 可根据项目情况调整
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (Objects.nonNull(authentication)) {
CustomerUserDetails userDetails = (CustomerUserDetails) authentication.getPrincipal();
this.strictInsertFill(metaObject, "createdBy", Long.class, Long.parseLong(userDetails.getId()));
this.strictUpdateFill(metaObject, "updateBy", Long.class, Long.parseLong(userDetails.getId()));
}
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (Objects.nonNull(authentication)) {
CustomerUserDetails userDetails = (CustomerUserDetails) authentication.getPrincipal();
this.strictUpdateFill(metaObject, "updateBy", Long.class, Long.parseLong(userDetails.getId()));
}
}
}
这样就完成了配置过程,需要自动更新数据的表只需要在实体类 extends AuditFields 即可