I have found the technique in the answer below very useful for transparently managing the created and updated timestamp for entities:
hard time setting autogenerated time with hibernate JPA annotations
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 = ??;
}
}
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.
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.
[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;
}