如果我添加/删除/更新可靠集合的元素,冬眠会增加版本吗? [英] Will hibernate increment version if I add/remove/update element of dependable collection?

查看:70
本文介绍了如果我添加/删除/更新可靠集合的元素,冬眠会增加版本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习休眠乐观锁定机制,但在用户指南

I am learning hibernate optimistic lock mechanism and I haven't found answer on my question in user guide

假设我们有这样的实体:

Let's say we have entity like this:

@Entity
class Employee{
    @Version
    Long versionField;

    List<Employee> subordinates;
    ...

}

在某个地方,我们有以下代码:

And somewhere we have following code:

Employee sub = ....
Emplyee emp = readEmploye();
emp.getSubordinates().add(sub);

在这种情况下可以控制版本增加吗?

Can I control of version incrementation at this case ?

推荐答案

默认为否.由于您不是要更改实体,而是要更改链接到该实体的其他实体.

By default no. Since you're not changing the entity, but rather other entities that are linked to it.

尽管有可能具有该功能,但是需要大量的配置,最好事先进行计划. 我不会复制Vlad Mihalcea的所有代码,

However it's possible to have that functionality, but it takes quite a bit of configuration and preferably planning in advance. I'm not going to duplicate all the code from the honourable Vlad Mihalcea, see here.

基本上,您需要使用事件侦听器来拦截保存调用,并使用RootAware接口(不是Hibernate接口,只是一个助手),要保存的子实体知道其根"并可以使用OPTIMISTIC_FORCE_INCREMENT锁定其父实体以增加其版本.

Basically you need to use event listeners to intercept the save calls, and using a RootAware interface (not a Hibernate interface, just a helper) a child entity being saved knows its "root" and can use the OPTIMISTIC_FORCE_INCREMENT lock on its parent entity to increase its version.

关于数据一致性:如果修改了子级或修改了父级(或两者都修改了),则刷新可能会失败,但是根实体上的lock()确保操作是原子的.如果根节点上的(悲观)锁成功,子节点上的(乐观)锁成功,则整个事务成功.由于使用了悲观锁,因此没有机会获得会破坏数据的半更新".

Regarding data consistency: the flushing can fail if the child was modified or the parent was modified (or both were), but the lock() on the root entity makes sure that the operation is atomic. If the (pessimistic) lock on the root succeeds, and the (optimistic) lock on the child succeeds, the complete transaction succeeds. Thanks to the pessimistic lock, there's no chance of getting "half updates" that would corrupt the data.

这篇关于如果我添加/删除/更新可靠集合的元素,冬眠会增加版本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆