【发布时间】:2015-06-10 22:45:56
【问题描述】:
我在实体属性上使用了@CreatedDate,我看到它将日期插入到数据库中。我不明白 Spring Data JPA 中 @CreatedBy 注释的目的是什么。
我们提供
@CreatedBy、@LastModifiedBy来捕获创建或修改实体的用户
但是如何创建和使用这样的用户呢?
【问题讨论】:
标签: java spring jpa spring-data spring-data-jpa
我在实体属性上使用了@CreatedDate,我看到它将日期插入到数据库中。我不明白 Spring Data JPA 中 @CreatedBy 注释的目的是什么。
我们提供
@CreatedBy、@LastModifiedBy来捕获创建或修改实体的用户
但是如何创建和使用这样的用户呢?
【问题讨论】:
标签: java spring jpa spring-data spring-data-jpa
如果您已经阅读了参考文档,我建议您阅读two more paragraphs 以了解以及如何使用AuditorAware。 :)
【讨论】:
对于 TL;DR
你的实体
@CreatedBy
private UUID modifyBy;
和您的 SecurityAuditorAware
@Component
public class SecurityAuditorAware implements AuditorAware<UUID> {
@Override
public Optional<UUID> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}
return Optional.of(((MyCustomUser) authentication.getPrincipal()).getId());
}
}
注意: 您需要使用相同的数据类型,我使用 UUID 作为我的自定义用户 ID。
【讨论】:
MyCustomUser 是从哪里来的?