Automatically configure createdBy and updatedBy in JPA objects

I am working on JPA (Hibernate implementation), Spring and the Stripes web application. I have several JPA objects that have the following common fields for audit and query purposes:

createdBy - user ID of the person who created the object. createdOn - object creation date updatedBy - identifier of the user who last updated the object updatedOn - date of the last update of the object

The application works for me, so createdOn and updatedOn are installed automatically when the object is saved, but I'm not sure how I can get the createdBy and updatedBy fields filled out without having to go through the current user ID from the controller class to the DAO.

Does anyone have any suggestions on how I can do this without passing user IDs everywhere? Please note that the current user ID is currently stored in the HttpSession object, so I need to access this data somehow ...

Thanks!

+6
spring hibernate jpa stripes
source share
3 answers

I decided that ThreadLocal is probably the cleanest way to do this in my application.

+1
source share

You can take a look at one of these approaches to pass the user ID as context in the business layer:

(Messages can still make a difference, even if you are not using EJB. A second post only makes sense if you use Spring with JTA)

I personally discourage this approach, as I perceive two problems with it:

  • Test: contextual data will need to be set in the test
  • Contract: contextual data is involved in the contract to use the object, but is not clearly visible in the interface.

Passing the user ID "everywhere" may seem like a lot of work, but I think it's cleaner.

To automatically set the date and user ID when creating or updating an object, you can use the EntityListener or lifecycle callbacks (maybe re already does this). Hope this helps ...

+3
source share

I would create a class like this:

@MappedSuperclass public abstract class AuditableDomainClass { private long createdBy; private long updatedBy; //getters and setters 

In your object classes that have a requirement that you described, it would just extend this class, you would set the variables in the layer that you need (for example, the controller), and you don’t need to worry about all this down in the DAO.

0
source share

All Articles