gpt4 book ai didi

Hibernate - 使用 all-delete-orphan 清除集合然后添加到它会导致 ConstraintViolationException

转载 作者:行者123 更新时间:2023-12-03 06:41:39 26 4
gpt4 key购买 nike

我有这些实体

class Foo{
Set<Bar> bars;
}

class Bar{
Foo parent;
String localIdentifier;
}

使用此映射(抱歉,没有注释,我很老式):

<class name="Foo">
...
<set name="bars" cascade="all-delete-orphan" lazy="false" inverse="true">
<key>...</key>
<one-to-many class="Bar"/>
</set>
</class>


<class name="Bar">
...
<property name="localIdentifier" column="local_identifier"/>
<many-to-one name="parent" column="parent_id" />
</class>

我对 2 列也有唯一约束:local_identifierparent_id (不是每列都有唯一约束,而是包含两者的单个唯一约束,例如没有 2 行允许具有相同的父级和相同的 localIdentifier)

alter table bar add constraint unique_bar unique (parent_id, local_identifier)

以及使用它们的代码:

//foo is persistent, foo id = 1
Bars bars = foo.getBars();
bars.clear(); // bars contained 1 item [parent_id = 1, local_identifier = "a"]
Bar newBar = new Bar();
newBar.setParent(foo);
newBar.setLocalIdentifier("a");
bars.add(newBar);

现在,由于某种原因,Hibernate 不会按照调用的顺序执行事物。它不会在 add() (插入)之前执行 clear() (删除),但反之亦然,它首先尝试插入,得到一个 ConstraintViolationException

我知道在 bars.clear(); 之后添加一点 session.flush() 可以解决这个问题,但在这种情况下,我无权访问以一种不难看的方式进行 session 。

那么冲洗是唯一的解决方案吗?或者是否有一个 Hibernate 版本尊重操作顺序?

更新:顺便说一句,取消引用集合将导致 https://www.hibernate.org/117.html#A3 出现 HibernateException。 :

I get HibernateException: Don't dereference a collection with cascade="all-delete-orphan" This will happen if you load an object with a cascade="all-delete-orphan" collection and then remove the reference to the collection. Don't replace this collection, use clear() so the orphan-deletion algorithm can detect your change.

最佳答案

我想除了冲洗之外别无选择

来自here :

Hibernate is violating a unique constraint!

Hibernate isn't quite as clever with unique constraints as it is with foreign keys. Sometimes you might need to give a little hint.

A unique constraint violation could occur if two objects are both being updated, one is "releasing" a value and the other is "obtaining" the same value. A workaround is to flush() the session manually after updating the first object and before updating the second.

(This kind of problem occurs rarely in practice.)

关于Hibernate - 使用 all-delete-orphan 清除集合然后添加到它会导致 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2065254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com