@CreatedBy如何在Spring Data JPA中运行?

Vol*_*kyi 10 java spring jpa spring-data spring-data-jpa

@CreatedDate在实体属性上使用,我看到它在db中插入日期.我不明白@CreatedBySpring Data JPA 中注释的目的是什么.

参考文档中,我读到:

我们提供@CreatedBy,@LastModifiedBy捕捉谁创建或修改该实体的用户

但是如何创建和使用这样的用户呢?

Oli*_*ohm 17

如果您已经参考了参考文档,我建议您阅读另外两个段落以了解和使用方法AuditorAware.:)


use*_*407 8

for TL;DR

your Entity

@CreatedBy
private UUID modifyBy;
Run Code Online (Sandbox Code Playgroud)

and your 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

note: you need use the same data type, I use UUID as my custom user id.

  • @Chris,它来自您的自定义用户工具,请检查[this](https://docs.spring.io/spring-security/site/docs/5.1.5.RELEASE/api/org/springframework/security/core/userdetails/用户.html) (2认同)