Does anyone know if it is possible to get Hibernate to use 1 for the version (optimistic locking field) of a new object instead of zero? My application previously used Eclipselink which starts at 1 and the change is causing some problems.
I am using JPA but expect any solution to be Hibernate specific (a property in persistence.xml hopefully!).
When ever we use versioning then hibernate inserts version number as zero, when ever object is saved for the first time in the database. Next time when we update this object, hibernate increments that version no by one automatically . In hibernate mapping file, add an element called version soon after id element.
Persist should be called only on new entities, while merge is meant to reattach detached entities. If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.
saveOrUpdate() Hibernate will check if the object is transient (it has no identifier property) and if so it will make it persistent by generating it the identifier and assigning it to session. If the object has an identifier already it will perform .
Good question, and it's not explicitly mentioned in the docs (even though it hints that it's possible). I also wasn't able to find any tests for this scenario, so, it may be a good improvement for the Hibernate test suite ;-)
Anyway, Hibernate will work as you expect if you map your @Version
property with a starting value:
@Version private int version = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With