https://blog.csdn.net/a3562323/article/details/106386099
重写插入方法:insertFill和修改方法:updateFill
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
try {
if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) { //判断对象有没有实现基础类,基础类中含有每张表必须的字段,例如创建时间,创建人等
BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime())
? baseEntity.getCreateTime() : new Date(); //判断创建时间是否空,不空:拿到这个时间,为空:获取当前时间
baseEntity.setCreateTime(current); //填充创建时间
baseEntity.setUpdateTime(current); //填充修改时间
String username = StringUtils.isNotBlank(baseEntity.getCreateBy())
? baseEntity.getCreateBy() : getLoginUsername();
// 当前已登录 且 创建人为空 则填充
baseEntity.setCreateBy(username);
// 当前已登录 且 更新人为空 则填充
baseEntity.setUpdateBy(username);
}
} catch (Exception e) {
throw new ServiceException("填充时间异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
}
}
@Override
public void updateFill(MetaObject metaObject) {
try {
if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
Date current = new Date();
// 更新时间填充(不管为不为空)
baseEntity.setUpdateTime(current);
String username = getLoginUsername();
// 当前已登录 更新人填充(不管为不为空)
if (StringUtils.isNotBlank(username)) {
baseEntity.setUpdateBy(username);
}
}
} catch (Exception e) {
throw new ServiceException("填充人员异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
}
}
/**
* 获取登录用户名
*/
private String getLoginUsername() {
LoginUser loginUser;
try {
loginUser = LoginHelper.getLoginUser();
} catch (Exception e) {
log.warn("获取用户信息失败 => 用户未登录");
return null;
}
return ObjectUtil.isNotNull(loginUser) ? loginUser.getUsername() : null;
}
}