简体   繁体   English

如何在实体更新中设置user_id?

[英]How to set user_id on Entity update?

I have entity with updatedAt and updatedBy audit fields. 我有带有updatedAtupdatedBy审核字段的实体。 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 ). 因此,对于脏检查,我可以使用Hibernate EmptyInterceptor接口(重写onFlushDirty()方法)或JPA侦听器( @PreUpdate )。 But how I can get current userId inside interceptor or listener? 但是,如何在拦截器或侦听器中获取当前的userId To my mind comes 2 solutions: 我想到2种解决方案:

  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 . userId传递到DAO层,以便我可以创建自定义拦截器,并将其传递给构造函数userId ,然后在创建新Session时使用此拦截器。

  2. Set current userId to public-static ThreadLocal variable so I have access to it from any place. 将当前的userId设置为public-static ThreadLocal变量,这样我就可以从任何地方访问它。

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). 请注意,我不能使用Envers库(它不符合我们的项目要求)。

Thanks. 谢谢。

I recommend storing the Person object in the Http session when the user authenticates. 我建议用户进行身份验证时将Person对象存储在Http会话中。 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. 我个人还将该实体分配给dao中的所需域对象,并且不使用@PreUpdate,因为我不希望该实体必须知道如何检索当前用户对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM