如何增加保存在Hibernate中的版本字段,无论是否脏或不? [英] How to increase a version field on save in Hibernate regardless if dirty or not?

查看:125
本文介绍了如何增加保存在Hibernate中的版本字段,无论是否脏或不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Hibernate和版本列来实现乐观并发控制。



问题:是否可以增加实体的版本号每次我将它保存到数据库时,无论它是否被更改?



只要某个字段在实体中更改,版本号获取增加。但是,如果实体中没有字段改变,实体的版本号保持不变。

这个问题背后的原因是我有一个逻辑的主 - 细节两个表之间的关系,并且我希望在详细信息发生变化时增加主表中的版本号,即使主数据没有变化。这种主从关系在Hibernate中没有映射。我只是总是将它们一起保存在一个事务中。

解决方案

您可以使用Hibernate拦截器来更新主记录的版本号当你确定细节已经改变时。

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html



一个限制是这个解决方案是特定于Hibernate的。 JPA还允许使用注释的事件驱动逻辑(例如PostPersist,PostUpdate等),但这些方法不允许您访问底层会话(更重要的是,文档警告您不要使用这些方法来修改会话数据)。我通常使用拦截器来执行审计,但是它们可以很容易地扩展到更改记录时更新版本号。


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.

解决方案

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.

这篇关于如何增加保存在Hibernate中的版本字段,无论是否脏或不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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