简体   繁体   English

休眠。 乐观的锁定。 即使生成它也会选择版本

[英]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. 如果实体被保存无论多少次,在事务结束时 Hibernate会选择该对象的版本。 Why? 为什么? Hibernate generates this version when it stores the object, so it knows it. Hibernate在存储对象时生成此版本,因此它知道它。 I found out that this method invokes this: 我发现这个方法调用了这个:

EntityVerifyVersionProcess#getCurrentVersion()

Hibernate generates this in logs: Hibernate在日志中生成:

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(). 我使用MySQL和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. 由于版本号由数据库管理,因此Hibernate执行额外的SQL语句以在更新后检索版本号。 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); 好吧,所以我没有写过以及似乎是什么问题是使用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. 这种情况不会在刷新时发生,因为Hibernate无论如何都会进行检查,但是在交易结束时,我认为,在覆盖数据时需要更加谨慎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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