Pregunta

I have a simple auditing requirement for my JPA entities : keep the creation and last modification date and author. The author should be the currently logged-in user.

I would like to implement this using @PrePersist and @PreUpdate annotations on a base class, or a JPA interceptor (no additional framework).

However, in both cases, I need a way to access the currently logged in user, which is stored in the HttpSession.

How can I access this information from a method on my base entity class or from a JPA interceptor ?

Is there any best practice or any tested method on how to achieve that ?

I was thinking, maybe add a web interceptor that, for each request, puts the logged-in user object into a globally reachable ThreadLocal (e.g. inside a Spring singleton service), which would make it possible to look it up from anywhere...

Does that sound like a good idea ?

Any suggestion welcome !

Edit: found similar question here (found it only after posting my own through suggestions on the right) : Setting createdBy and updatedBy in JPA entities automatically

The conclusion seems to go in the direction of ThreadLocal... still, any feedback welcome !

¿Fue útil?

Solución

If you do not use remote (EJB) calls then the idea to use ThreadLocal should work, as most containers use one thread for each request processed. You need to be careful when you put the user and when you delete it, as the container probably uses a thread pool and you don't want to leave the user object attached to a thread that might be used to process another request.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top