小编典典

@CreatedBy和@LastModifiedBy设置实际实体而不是id

spring-boot

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

@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 set成为实体上的实际User,而不仅仅是其id?

谢谢


阅读 2475

收藏
2020-05-30

共1个答案

小编典典

这似乎可以由文档直接回答:

如果您使用@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实例。我们在这里假设您通过UserDetails实现公开域用户,但是根据找到的身份验证,您还可以从任何地方查找它。

2020-05-30