I have the need to capture who created and last modified a number of the entities in our system.
Our entites have fields for created by, modified by, creation date, and modification date.
What is the recommended way to do this?
My thinking was that I could update these fields using the PrePersist and PreUpdate entity callbacks. Unfortunately, the entity doesn't have access to the SessionContext where the information about the caller subject is.
My DAO beans have access to the SessionContext so one approach might be to get the caller subject from the SessionContext and set it on a thread-local (via an aspect most likely) before manipulating the entities. Then the entities would have that data available.
There are two problems with this. First, it feels hackish so I'm guessing there is a better way. Second, if there is a UserTransaction running, the entities don't actually get persisted (and the callbacks don't get called) until the transaction is committed at which point the DAO method(s) are no longer in the execution stack and the call is being handled by a completely different thread, etc. So basically, that idea just doesn't work at all.
Seems like this is a pretty common thing to want to do so I'm guessing there is a recommended way to do it.
You could try retrieving the current principal from the entity session context (not sure if this is possible) and populate during @PrePersist.
Would like to know if this works :-)