Setting createdBy and updatedBy in JPA entities automatically

怎甘沉沦 提交于 2019-12-03 14:11:08

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

(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...

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

I'd create a class like this:


@MappedSuperclass
public abstract class AuditableDomainClass {
  private long createdBy;
  private long updatedBy;

  //getters and setters

Your entity classes that have the requirement you've described would simply extend this class, you'd set you variables in the layer you need to (controller for example) and you don't need to worry about it all the way down in the DAOs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!