Jpa - Hibernate @Version incorrectly incremented

妖精的绣舞 提交于 2019-12-03 11:36:26

I would say this is an expected behavior. According to the Hibernate manual, @PreUpdate is "Executed before the database UPDATE operation.". So, Hibernate has already figured out it has to do UPDATE by running the dirty check, and having it return true.

The dirty check can't happen AFTER @PreUpdate, because Hibernate shouldn't call @PreUpdate unless the dirty check is true. And if an update is going to be run, version should be incremented.

Have you thought about using a listener for @PrePersist, instead of @PreUpdate? I believe that's early enough in the process that it would be pre-dirty check, and thus have the behavior that you want.

For me it looks like specification violation. Or maybe that is too strong wording, better probably to say that such a corner case is not clearly enough specified. JPA 1.0 (Hibernate 3.2.7 being one of the implementations) specification spells quite clearly when version should be updated:

The version attribute is updated by the persistence provider runtime when the object is written to the database.

Also setting basic attribute in invoked entity is aloud (JPA 2.0):

A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.

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