gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:00:37 24 4
gpt4 key购买 nike

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

@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 auditinginfrastructure somehow needs to become aware of the current principal.To do so, we provide an AuditorAware SPI interface that you have toimplement to tell the infrastructure who the current user or systeminteracting with the application is. The generic type T defines whattype the properties annotated with @CreatedBy or @LastModifiedBy haveto be.

The following example shows an implementation of the interface thatuses 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 thecustom UserDetails instance that you have created in yourUserDetailsService implementation. We assume here that you areexposing the domain user through the UserDetails implementation butthat, based on the Authentication found, you could also look it upfrom anywhere.

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com