如果我更新子级,父级的版本属性不会增加
我将 JPA 2 与 Hibernate 3.x 一起使用。我有两个实体对象 Foo 和 Bar,关系是这样的 -
@Entity
public class Foo{
@Id
private long id;
@OneToOne(cascade = CascadeType.ALL )
@JoinColumn(name = "bar")
private Bar bar;
@Version
private int version;
}
@Entity
public class Bar{
@Id
private long id;
private String name;
@Version
private int version;
}
现在我的问题是如果我从 entityManager.find(...)
加载 Foo
并更新
,例如 Bar
的 >namefoo.getBar().setName("someAnotherName");
并触发 entityManager.merge(foo)
然后 Hibernate 会触发 Bar
上的更新,并仅增加 Bar
的版本。从对象的角度来看,这不也是 Foo 状态的变化吗?难道它不应该增加 Foo 的版本吗?
现在我想从 Bar
中删除 version
属性,如果 的话,
已更新。 我怎样才能实现这个目标?Foo
的 version
应该增加栏
I'm using JPA 2 with Hibernate 3.x. I have two Entity objects Foo and Bar and the relation is like this -
@Entity
public class Foo{
@Id
private long id;
@OneToOne(cascade = CascadeType.ALL )
@JoinColumn(name = "bar")
private Bar bar;
@Version
private int version;
}
@Entity
public class Bar{
@Id
private long id;
private String name;
@Version
private int version;
}
Now my problem is If I loaded Foo
from entityManager.find(...)
and updated name
of Bar
like foo.getBar().setName("someAnotherName");
and fire entityManager.merge(foo)
then Hibernate fires a update on Bar
and increments a version for Bar
only. From the object perspective doesn't its a change of the sate of Foo as well and shouldn't it increment the version of Foo as well?
Now I would like to remove the version
property from Bar
and version
of Foo
should get incremented if Bar
gets updated.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的情况下,不是 Foo,而是它引用的实体已更改,因此不需要版本增量。
@Version 向实体添加乐观锁定功能,并且不应将其用作更改计数器。此注释的主要目的是检测冲突的更新,因此在执行此操作之前请三思。
覆盖此行为的唯一方法是使用 [OPTIMISTIC |悲观]_FORCE_INCREMENT
In your case not Foo, but entity on which it references has been changed, so there is no need in version increment.
@Version adds optimistic locking capability to an entity and it shouldn't be used as a change counter. The main purpose of this annotation is detecting of conflicting updates, so think twice before doing that.
The only way to override this behaviour is to use [OPTIMISTIC | PESSIMISTIC]_FORCE_INCREMENT