问题
I have entity with updatedAt
and updatedBy
audit fields. I want to set this fields only if entity state was changed. So, for dirty checking I can use either Hibernate EmptyInterceptor
interface (overriding onFlushDirty()
method) or JPA listeners (@PreUpdate
). But how I can get current userId
inside interceptor or listener? To my mind comes 2 solutions:
Pass
userId
to DAO layer, so I can create custom interceptor passing to it constructoruserId
and then use this interceptor when creating newSession
.Set current
userId
to public-staticThreadLocal
variable so I have access to it from any place.
But I think both approaches are ugly. So may be there is exist some more elegant way to solve my problem?
Please note, I can't use Envers
library (it don't fit our project requirements).
Thanks.
回答1:
I recommend storing the Person object in the Http session when the user authenticates. This way you can grab it from the session and use the merge functionality in the entity manager to convert it back to an attached entity.
I personally also assign the entity to the requiring domain object in the dao and do not use the @PreUpdate because I do not want the entity to have to know how to retrieve the current user object.
来源:https://stackoverflow.com/questions/20620406/how-to-set-user-id-on-entity-update