我有一个看起来像这样的实体:
@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 ?
Thanks
这似乎很直接地回答了文档 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#auditing.auditor-aware:
如果您使用@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 对象并查找
您在中创建的自定义 UserDetails 实例
UserDetailsService 实现。我们在这里假设您是
通过 UserDetails 实现公开域用户,但是
根据找到的身份验证,您还可以查找它
来自任何地方。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)