【问题标题】:How does @CreatedBy work in Spring Data JPA?@CreatedBy 如何在 Spring Data JPA 中工作?
【发布时间】:2015-06-10 22:45:56
【问题描述】:

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

reference documentation我读到:

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

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

【问题讨论】:

    标签: java spring jpa spring-data spring-data-jpa


    【解决方案1】:

    如果您已经阅读了参考文档,我建议您阅读two more paragraphs 以了解以及如何使用AuditorAware。 :)

    【讨论】:

      【解决方案2】:

      对于 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 是从哪里来的?
      • @Chris 它来自您的自定义用户工具,请查看this
      猜你喜欢
      • 2015-12-17
      • 1970-01-01
      • 2017-11-29
      • 2017-06-01
      • 2015-06-18
      • 2018-11-29
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多