我有一个看起来像这样的实体:
@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/