在JPA实体上透明地记录上次修改的用户 [英] Transparently recording the last modified user on JPA entity
问题描述
我发现以下答案中的技术对于透明地管理实体的创建和更新时间戳非常有用:
I have found the technique in the answer below very useful for transparently managing the created and updated timestamp for entities:
使用hibernate JPA注释设置自动生成时间的困难时期
我想知道是否有类似的东西用于记录实体的创建和更新用户?
I am wondering if there is something similar for recording the create and update user for the entity?
@PreUpdate
@PrePersist
public void updateAudit() {
lastModifiedDate = new Date();
lastModifiedUser = ??;
if (dateCreated==null) {
dateCreated = new Date();
userCreated = ??;
}
}
新日期()
在示例中提供了当前时间,我无法找到可以存储用户ID的位置(在登录时),该位置可以从实体上的@PrePersist注释方法访问。
While new Date()
in the example provides the current time, I am having trouble finding a location in which the user id could be stored (at logon time) which is accessible from a @PrePersist annotated method on an entity.
使用 @Produces
方法注入 @LoggedInUser
将是理想但我的实体是由 new()
创建的,而不是通过注入创建,所以不管理。
Injecting a @LoggedInUser
with a @Produces
method would be ideal but my entities are created by new()
rather than by injection so are not managed.
我是对此我很陌生,所以我希望我错过了一些明显的东西。谢谢。
I'm pretty new to this so I hope I'm missing something obvious. Thanks.
下面从prunge回答导致代码(删节)
[edit] Answer below from prunge led to code (abridged)
@MappedSuperclass
public abstract class BaseEntity implements Serializable, Comparable<BaseEntity> {
@Version
private Timestamp updatedTimestamp;
private static ThreadLocal<Long> threadCurrentUserId = new ThreadLocal<Long>();
/* Called from entry point like servlet
*/
public static void setLoggedInUser(BaseEntity user) {
if (user!=null) threadCurrentUserId.set(user.getId());
}
@PrePersist
@PreUpdate
protected void onCreateOrUpdate() {
//Note we don't have to update updatedTimestamp since the @Version annotation does it for us
if(createdTimestamp==null) createdTimestamp = new Timestamp(new Date().getTime());;
lastUpdatedByUserId = threadCurrentUserId.get();
if(createdByUserId==null) createdByUserId = lastUpdatedByUserId;
}
推荐答案
如果是webapp,你就是可以使用ThreadLocal存储当前用户。
If it's a webapp, you could use a ThreadLocal for storing the current user.
- 在servlet过滤器中设置ThreadLocal值,从servlet请求中读取用户。
- 从JPA实体中读取ThreadLocal值。
- 清除通过过滤器返回的值。
这篇关于在JPA实体上透明地记录上次修改的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!