Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting createdBy and updatedBy in JPA entities automatically

I'm working on a JPA (Hibernate implementation of), Spring and Stripes web app. I have a number of JPA entities that have the following fields in common for both audit and query purposes:

createdBy - the user ID of the person who created the entity. createdOn - the date the entity was created updatedBy - the user ID of the person who last updated the entity updatedOn - the date the entity was last updated

I've got my app working so that createdOn and updatedOn are set automatically when the entity is persisted but I'm not sure how I can get the createdBy and updatedBy fields populated without having to pass through the currently logged in user's ID all the way from the controller class to the DAOs.

Does anyone have any suggestions on how I might do this without passing userIDs all over the place? Note that the current user ID is stored in the HttpSession object at the moment, so my backend needs to somehow access this data...

Thanks!

like image 412
JMM Avatar asked Dec 08 '09 07:12

JMM


1 Answers

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

  • How To Pass Context Between Layers With ThreadLocal And EJB 3
  • How To Pass Context In Standard Way - Without ThreadLocal

(The posts may still be relevant even if you're not using EJB. The second post make sense however only if you use Spring with JTA)

I personally discourage these approach, as I perceive two problem with it:

  • Testability: contextual data will need to be set up in the test
  • Contract: contextual data participate in the contract to use the entity but is not clearly visible in the interface.

Passing userID "all over the place" may seem like a big job, but I think it's cleaner.

To set the date and user ID automatically when entity is created or update, you can use an EntityListener or lifecycle callbacks (maybe you're already doing that). Hope it helps...

like image 61
ewernli Avatar answered Oct 26 '22 18:10

ewernli