自动设置JPA实体中的createdBy和updatedBy
我正在开发 JPA(Hibernate 实现)、Spring 和 Stripes Web 应用程序。我有许多 JPA 实体,它们具有以下共同字段,用于审计和查询目的:
创建者 - 创建实体的人员的用户 ID。 createdOn - 实体创建的日期 UpdatedBy - 最后更新实体的人的用户ID UpdatedOn - 实体上次更新的日期
我已经让我的应用程序正常工作,以便在实体持久化时自动设置createdOn和updatedOn,但我不确定如何在不通过的情况下填充createdBy和updatedBy字段当前登录用户的 ID 从控制器类一直到 DAO。
有人对我如何在不到处传递用户 ID 的情况下做到这一点有任何建议吗?请注意,当前用户 ID 目前存储在 HttpSession 对象中,因此我的后端需要以某种方式访问此数据...
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以查看以下方法之一,将用户 ID 作为上下文传递到业务层:
(即使您不使用 EJB,这些帖子可能仍然相关。但只有当您将 Spring 与 JTA 一起使用时,第二篇文章才有意义)
我个人不鼓励使用这些方法,我认为它有两个问题:
“到处”传递 userID 似乎是一项艰巨的工作,但我认为它更干净。
要在创建或更新实体时自动设置日期和用户 ID,您可以使用 EntityListener 或生命周期回调(也许您已经这样做了)。
希望它有帮助...
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:
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...
我认为 ThreadLocal 可能是在我的应用程序中执行此操作的最简洁的方法。
I've decided that a ThreadLocal is probably the cleanest way to do this in my application.
我会创建一个这样的类:
具有您所描述的要求的实体类将简单地扩展此类,您可以在需要的层(例如控制器)中设置变量,并且不需要一直在 DAO 中担心它。
I'd create a class like this:
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.