java @CreatedBy 如何在 Spring Data JPA 中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29472931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:20:31  来源:igfitidea点击:

How does @CreatedBy work in Spring Data JPA?

javaspringjpaspring-dataspring-data-jpa

提问by Volodymyr Levytskyi

I used @CreatedDateon entity property and I see that it inserts date into db. I don't understand what is the purpose of @CreatedByannotation in Spring Data JPA.

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

In the reference documentationI read :

在我阅读的参考文档中

We provide @CreatedBy, @LastModifiedByto capture the user who created or modified the entity

我们提供@CreatedBy,@LastModifiedBy以捕获创建或修改实体的用户

But how to create and use such user?

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

回答by Oliver Drotbohm

If you already made it to the reference documentation, I recommend to read two more paragraphsto find out about and how to use AuditorAware. :)

如果您已经阅读了参考文档,我建议您再阅读两段以了解以及如何使用AuditorAware. :)

回答by user1686407

for TL;DR

对于 TL; DR

your Entity

你的实体

@CreatedBy
private UUID modifyBy;

and your SecurityAuditorAware

和您的 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());
    }
}

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

注意:您需要使用相同的数据类型,我使用 UUID 作为我的自定义用户 ID。