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

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

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

@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?

谢谢

最佳答案

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

In case you use either @CreatedBy or @LastModifiedBy, the auditing infrastructure somehow needs to become aware of the current principal. To do so, we provide an AuditorAware SPI interface that you have to implement to tell the infrastructure who the current user or system interacting with the application is. The generic type T defines what type the properties annotated with @CreatedBy or @LastModifiedBy have to be.

The following example shows an implementation of the interface that uses Spring Security’s Authentication object:

Example 104. Implementation of AuditorAware based on Spring Security

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);   
  } 
} 

The implementation accesses the Authentication object provided by Spring Security and looks up the custom UserDetails instance that you have created in your UserDetailsService implementation. We assume here that you are exposing the domain user through the UserDetails implementation but that, based on the Authentication found, you could also look it up from anywhere.

关于java - @CreatedBy 和@LastModifiedBy 设置实际实体而不是 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658463/

相关文章:

java - 如何在 spring boot 属性文件中使用时间戳?

java - 使用 spring security 验证失败后重定向回原始页面

Java 桥接错误

java - JNLP、Webstart 和 Maven

java - 一致高效的双向数据结构实现(Java)

java - 如何制作基于构造函数或 setter 的依赖注入(inject)?

java - Wicket 的 LDAP 身份验证

spring-boot - 如何从 GitLab 存储库将 Web 应用程序部署到 AWS 实例

java - Spring : HttpSession returned null object for SPRING_SECURITY_CONTEXT in Clusterd Tomcat failover

spring-boot - io.jsonwebtoken.SignatureException : JWT signature does not match locally computed signature