如何解决向@CreatedBy添加更多信息
我有一个Spring Boot 2.3应用程序。我所有的实体都扩展了一个抽象的实体,该实体具有一些审核字段,例如:
@CreatedBy
@Column(updatable = false)
protected String createdBy;
@CreatedDate
@Column(nullable = false,updatable = false)
protected Instant createdDate;
我实现了AuditorAware
:
public class SpringSecurityAuditorAware implements AuditorAware<String> {
public static final String SYSTEM_USER = "system";
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.of(SYSTEM_USER);
}
Object principal = authentication.getPrincipal();
/**
* If the principal is a CustomUserDetail I access to the name property
*/
if (principal instanceof CustomUserDetail) {
CustomUserDetail user = (CustomUserDetail) principal;
// the sid of the user if not null or the username instead
String sid = user.getSid() != null ? user.getSid() : user.getUsername();
return Optional.ofNullable(sid);
}
return Optional.of(authentication.getName());
}
}
在createdBy
字段中,保存用户的sid(标识符)。这样,我就可以引用源表,并且可以在所有更改和用户之间保持链接。
但是,出于性能原因,我还要在每个实体中保存用户的全名。
有没有一种干净的方法可以达到这个目标?我唯一想到的就是使用EntityListener
并在createdByName
上设置@PrePersist
。
@Component
public class MyEntityListener {
@PrePersist
private void onPrePersist(MyAbstractEntity entity) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
if (principal instanceof CustomUserDetail) {
CustomUserDetail user = (CustomUserDetail) principal;
entity.setCreatedByName(user.getFullName());
}
}
}
}
您如何看待?您还有其他更好/更清洁的方法吗?
解决方法
注释为@CreatedBy
的字段可以是任何类型。我认为一种方法可能是创建一个具有AuditUser
和userId
之类的字段的userFullName
类,并将其注释为@Embeddable
(以防{{1} },以声明希望如何命名表列)。然后,在您的实体中,您可以将一个@AttributeOverrides
字段用AuditUser
和@CreatedBy
注释,并结合一个@Embedded
的实现。此blog post(Baeldung)中有关可嵌入对象的更多信息。
如果您需要更具体的内容,可以考虑从Spring实施JPA审核的方式启发来创建一些自定义的内容(查看类AuditorAware<AuditUser>
,AuditingEntityListener
和AuditingHandler
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。