Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Hibernate to start version column at 1 for new objects?

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!).

like image 967
David Tinker Avatar asked Jan 28 '11 09:01

David Tinker


People also ask

How does hibernate versioning work?

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.

What is difference between persist and merge in hibernate?

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.

How does saveOrUpdate work in hibernate?

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 .


1 Answers

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;
like image 116
jpkrohling Avatar answered Sep 27 '22 16:09

jpkrohling