实体类基类
BaseEntity.java
@MappedSuperclass
public abstract class BaseEntity {
private LocalDateTime createdDate;
private LocalDateTime lastModifiedDate;
private String createdBy;
private String lastModifiedBy;
@PrePersist
protected void onCreate() {
createdDate = LocalDateTime.now();
lastModifiedDate = createdDate;
String currentUser = getCurrentUserFromContext();
if (currentUser != null) {
createdBy = currentUser;
lastModifiedBy = currentUser;
}
// 如果 currentUser == null,你可以选择:
// - 抛异常(不允许无用户操作)
// - 设为 "SYSTEM"
// - 或者保留 null(但首次必须有值?)
}
@PreUpdate
protected void onUpdate() {
lastModifiedDate = LocalDateTime.now();
String currentUser = getCurrentUserFromContext();
if (currentUser != null) {
lastModifiedBy = currentUser;
}
// 👉 关键:如果 currentUser 为空,就不更新 lastModifiedBy,保留旧值!
}
private String getCurrentUserFromContext() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.isAuthenticated()) {
return null;
}
Object principal = auth.getPrincipal();
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
} else if (principal instanceof String) {
return (String) principal;
}
return null;
}
// getters/setters...
}