如何在 Hibernate 中保存时增加版本字段,无论是否脏?
我使用带有版本列的 Hibernate 来实现乐观并发控制。
问题:每次将实体保存到数据库时,无论是否更改,是否可以增加实体的版本号?
只要实体中的某些字段发生更改,版本号 就会增加数量增加。但是,如果实体中没有字段发生更改,则实体的版本号保持不变。
这个问题背后的原因是,我在两个表之间建立了逻辑主从关系,并且每当细节发生变化时,我想增加主表中的版本号,即使主数据没有改变。这种主从关系在 Hibernate 中没有映射。我总是将它们保存在一个事务中。
I'm using Hibernate with a version column to implement optimistic concurrency control.
The question: Is it possible to increment the version number of an entity every time I save it to database, regardless if it was changed or not?
As long as some field is changed in the entity, the version number gets increased. But, if no field changed in the entity, the version number of the entity stays unchanged.
The reason behind this question is that I've got a logical master-detail relationship between two tables and I'd like to increase the version number in the master table whenever something changes in details, even if master data didn't change. This master-detail relationship is not mapped in Hibernate. I just always save them together in a single transaction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您发现详细信息已更改时,您可以使用 Hibernate 拦截器来更新主记录的版本号。
http://docs.jboss.org/hibernate/core /3.3/reference/en/html/events.html
一个限制是该解决方案特定于 Hibernate。 JPA 还允许使用注释的事件驱动逻辑(例如 PostPersist、PostUpdate 等),但这些方法不允许您访问底层会话(更重要的是,文档警告您不要使用这些方法来修改会话)数据)。我通常使用拦截器来执行审核,但它们可以轻松扩展以在记录更改时更新版本号。
You can use Hibernate interceptors to update the version number of the master record when you identify that a detail has changed.
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html
One limitation is that this solution is specific to Hibernate. JPA also allows event-driven logic using annotations (e.g. PostPersist, PostUpdate, etc...) but these methods don't give you access to the underlying session (and, more importantly, the documentation cautions you from using these methods to modify session data). I've typically used interceptors to perform auditing, but they could easily be extended to update a version number when a record is altered.
您可以通过
LockMode.OPTIMISTIC_FORCE_INCRMENT
调用lock()
(或使用采用LockMode
的其他方法)。You can call
lock()
(or use other methods that takeLockMode
) withLockMode.OPTIMISTIC_FORCE_INCREMENT
.