I have an entity:
<class name="name.dargiri.model.Entity" table="ENTITY" optimistic-lock="version">
<version name="version" column="ver" type="long" />
</class
If the Entity is saved no matter how many times, in the end of transaction Hibernate selects for the version of the object. Why? Hibernate generates this version when it stores the object, so it knows it. I found out that this method invokes this:
EntityVerifyVersionProcess#getCurrentVersion()
Hibernate generates this in logs:
Hibernate:
/* update
name.dargiri.model.Entity */ update
ENTITY
set
ver=?,
USERNAME=?,
lucky_number=?
where
id=?
and ver=?
Hibernate:
/* get version name.dargiri.model.Entity */ select
ver
from
ENTITY
where
id =?
I use MySQL and Session#save().
Okay, so what I didn’t write about and what appeared to be the problem is using LockMode.OPTIMISTIC:
session.get(Entity.class, 1L, LockMode.OPTIMISTIC);It appeared that this is how this lock mode works – it checks at the end of the transaction whether no one changed the version of the object so far. And this happens not while flushing, because Hibernate will anyway do the check, but by the end of the transaction, which is, I think, additional option to be more careful about overwriting data.