How to increase a version field on save in Hiberna

2019-07-18 13:36发布

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.

2条回答
Deceive 欺骗
2楼-- · 2019-07-18 13:43

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.

查看更多
太酷不给撩
3楼-- · 2019-07-18 13:56

You can call lock() (or use other methods that take LockMode) with LockMode.OPTIMISTIC_FORCE_INCREMENT.

查看更多
登录 后发表回答