【问题标题】:@CreatedBy and @LastModifiedBy set actual entity instead of id@CreatedBy 和 @LastModifiedBy 设置实际实体而不是 id
【发布时间】:2019-05-08 13:36:09
【问题描述】:

我有一个看起来像这样的实体:

@Audited
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {

  public static final long UNSAVED = 0;

  @Id
  @GeneratedValue
  private long id;

  @CreatedDate
  @Column(name = "created_at", updatable = false)
  private ZonedDateTime createdAt;

  @CreatedBy
  @OneToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "created_by")
  private User createdBy;

  @LastModifiedDate
  private ZonedDateTime updatedAt;

  @OneToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "updated_by")
  @LastModifiedBy
  private User updatedBy;

}

我想要@LastModifiedBy 和@CreatedBy 以便他们设置相应的用户。但是,当我尝试保存实体时,出现异常:

java.lang.ClassCastException: Cannot cast java.lang.Long to com.intranet.users.Users

所以在我看来,它试图设置的不是实际用户,而是 id。有什么方法可以让 spring 在实体上设置实际用户而不仅仅是它的 id?

谢谢

【问题讨论】:

  • 最好使用String而不是User private String createdBy;进行审计

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


【解决方案1】:

the documentation 似乎直接回答了这个问题:

如果您使用@CreatedBy 或@LastModifiedBy,审计 基础设施需要以某种方式了解当前的委托人。 为此,我们提供了一个 AuditorAware SPI 接口,您必须 实现告诉基础设施当前用户或系统是谁 与应用程序的交互是。泛型类型 T 定义了什么 键入带有 @CreatedBy 或 @LastModifiedBy 注释的属性 成为。

以下示例显示了接口的实现 使用 Spring Security 的 Authentication 对象:

示例 104. 基于 Spring Security 的 AuditorAware 实现

class SpringSecurityAuditorAware implements AuditorAware<User> {

  public Optional<User> getCurrentAuditor() {

    return Optional.ofNullable(SecurityContextHolder.getContext())
        .map(SecurityContext::getAuthentication)
        .filter(Authentication::isAuthenticated)
        .map(Authentication::getPrincipal)
        .map(User.class::cast);   
  } 
} 

实现访问 Spring Security 提供的 Authentication 对象并查找 您在您的 UserDetailsS​​ervice 实现。我们在这里假设您是 通过 UserDetails 实现公开域用户,但 即,根据找到的身份验证,您还可以查找它 从任何地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多