Java @CreatedBy和@LastModifiedBy设置实际实体而不是id
我有一个实体,看起来像:Java @CreatedBy和@LastModifiedBy设置实际实体而不是id,java,spring-boot,spring-security,spring-data-jpa,spring-data,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 = "cre
@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
谢谢这似乎可以通过以下方式直接回答: 如果使用@CreatedBy或@LastModifiedBy,则审计 基础设施需要意识到当前的主体。 为此,我们提供了一个AuditorAware SPI接口,您必须 实施以告知基础架构当前用户或系统是谁 与应用程序进行交互是非常重要的。泛型类型T定义了什么 键入带有@CreatedBy或@LastModifiedBy注释的属性 是的 下面的示例显示了 使用Spring Security的身份验证对象: 例104。基于Spring安全性的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);
}
}
类SpringSecurityAuditorAware实现AuditorAware{
公共可选getCurrentAuditor(){
返回可选的.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter(身份验证::isAuthenticated)
.map(身份验证::getPrincipal)
.map(User.class::cast);
}
}
实现访问Spring Security提供的身份验证对象并查找
您在中创建的自定义UserDetails实例
UserDetailsService实现。我们假设你是
通过UserDetails实现公开域用户,但
根据找到的身份验证,您还可以查找它
从任何地方来
最好用字符串审计,而不是用户
private String createdBy代码>