How to set user_id on Entity update?

冷暖自知 提交于 2019-12-11 16:46:49

问题


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:

  1. Pass userId to DAO layer, so I can create custom interceptor passing to it constructor userId and then use this interceptor when creating new Session.

  2. Set current userId to public-static ThreadLocal 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

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