简体   繁体   中英

Hibernate. Optimistic lock. Selects version even though it generates it

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

Hibernate performs an extra SQL statement to retrieve the version number after the update has been made because the version number is managed by the database. For more details, I suggest you take a look at this article which explains this very well.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM