Hibernate的@Version可以考虑相关实体的更改吗? [英] Can Hibernate's @Version consider changes in related entities?

查看:128
本文介绍了Hibernate的@Version可以考虑相关实体的更改吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实体:一对多关系中的ParentChild. Parent是版本控制的,即具有@Version字段.我的目标是同步对Parent版本的ParentChild实体的更改.

例如一个线程更新Parent,另一个线程更新它的Child,这将导致OptimisticLockException.

有可能吗?

我尝试在Child上添加@PreUpdate,这会增加它的Parent版本,但这没有帮助,因为Hibernate似乎仅在检查版本后才执行侦听器,因此事务无论如何都成功提交. /p>

如果可能,如何实施?

解决方案

首先,这里需要澄清两个问题:

  1. 我认为您正在尝试捕获对特定Child实例所做的更新,而不是集合修改(例如,添加了新的Child或删除了旧的Child).后者将默认增加父级的版本.

  2. 当您说一个线程更新父级"和另一个更新子级"时,我假设所做的更改会立即被刷新.换句话说,事件的顺序为:父级已更新并持久(更改已刷新;事务已提交 1 );另一个线程尝试更新指向父代先前版本的子代,但失败.如果不是这种情况,乐观锁定将无法为您提供帮助.

1 您可以通过设置适当的隔离级别来解决事务提交"位的问题,但这可能会导致更多问题,然后在并发环境中解决.您无法解决立即冲洗"的要求.

假设以上假设正确无误,则需要使用 EntityManager.lock()方法可在更新Child实例之前锁定父级.请参见 LockModeType 休眠EntityManager文档.

I have 2 entities: Parent and Child in a one-to-many relationship. The Parent is versioned, i.e. has a @Version field. My goal is to synchronize changes to both Parent and Child entities on the Parent's version.

E.g. one thread updates the Parent and another one updates one of it's Childs, this should cause an OptimisticLockException.

Is it possible?

I tried adding a @PreUpdate to the Child which would increment the version of it's Parent, but that didn't help because Hibernate seems to execute listeners only after it checks versions so the transaction commits successfully anyway.

If it is possible, how can it be implemented?

解决方案

First of all, there are two issues here that need to be clarified:

  1. I take it you're trying to catch updates made to a particular Child instance rather than collection modifications (e.g. new Child being added / old removed). The latter will increment parent's version by default.

  2. When you say "one thread updates Parent" and "another updates Child" I'm assuming that changes are immediately flushed. In other words, the sequence of events is: parent is updated and persisted (changes flushed; transaction committed1); another thread tries to update child which points to the previous version of parent and fails. If that's not the case, optimistic locking is not going to help you.

1 You may be able to work around the "transaction committed" bit by setting appropriate isolation level, but that's likely to cause more problems then it solves in concurrent environment. You can't work around "immediate flush" requirement.

Assuming the above assumptions are correct, you'll need to use EntityManager.lock() method to lock Parent prior to updating your Child instance. See LockModeType and Hibernate EntityManager docs for details.

这篇关于Hibernate的@Version可以考虑相关实体的更改吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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