How to increase a version field on save in Hibernate regardless if dirty or not?

与世无争的帅哥 提交于 2019-12-12 19:40:21

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5990766/how-to-increase-a-version-field-on-save-in-hibernate-regardless-if-dirty-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!