如何在实体更新上设置user_id? [英] How to set user_id on Entity update?

查看:152
本文介绍了如何在实体更新上设置user_id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 updatedAt updatedBy 审计字段的实体。我只想在实体状态改变的情况下设置这个字段。因此,对于脏检查,我可以使用Hibernate EmptyInterceptor 接口(覆盖 onFlushDirty()方法)或JPA侦听器( @PreUpdate )。但是,我如何在拦截器或侦听器中获取当前 userId ?在我看来,有两个解决方案:


  1. 传递给DAO层 userId ,所以我可以创建自定义拦截器传递给它的构造函数 userId ,然后在创建新的 Session 时使用这个拦截器。设置当前 userId 为public-static ThreadLocal 变量,所以我可以从任何地方访问它。


但我认为这两种方法都很难看。那么可能存在一些更优雅的方式来解决我的问题?



请注意,我不能使用 Envers 库(它不符合我们的项目要求)。



谢谢。

解决方案

我建议在用户验证时将Person对象存储在Http会话中。通过这种方式,您可以从会话中抓取它,并使用实体管理器中的合并功能将其转换回附加的实体。



我个人也将实体分配给dao中的require域对象,并且不要使用@PreUpdate,因为我不希望实体必须知道如何检索当前的用户对象。

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.

解决方案

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.

这篇关于如何在实体更新上设置user_id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆