java Hibernate 在更新唯一键的字段部分时抛出唯一约束违反异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3524217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate throws unique constraint violation exception while updating field part of unique key
提问by Cshah
Below is the use case: I have a unique index defined on 3 columns say A,B,C. Assume the values in them are A1,B1,C1. My java code is adding a new record say A1,B1,C1 but before this record is added, i update the previous value from C1 to C2. While trying to add the new record (after the update), hibernate is throwing an unique constraint violation exception. Any reason as to why it does? All the above statements are executed within the same transaction. My assumption is the insert happens before the update and hence the reason for the exception.
下面是用例:我在 3 列上定义了一个唯一索引,比如 A、B、C。假设其中的值为 A1、B1、C1。我的 Java 代码正在添加一条新记录,比如 A1、B1、C1,但在添加此记录之前,我将先前的值从 C1 更新为 C2。在尝试添加新记录时(更新后),hibernate 抛出一个唯一的约束冲突异常。有什么理由说明为什么会这样吗?以上所有语句都在同一个事务中执行。我的假设是插入发生在更新之前,因此是异常的原因。
Any thoughts/suggestions ?
任何想法/建议?
采纳答案by Rafael
Try to use session.flush() after the update.
尝试在更新后使用 session.flush()。
回答by Pascal Thivent
My java code is adding a new record say A1,B1,C1 but before this record is added, i update the previous value from C1 to C2. While trying to add the new record (after the update), hibernate is throwing an unique constraint violation exception. Any reason as to why it does? All the above statements are executed within the same transaction.
我的 Java 代码正在添加一条新记录,比如 A1、B1、C1,但在添加此记录之前,我将先前的值从 C1 更新为 C2。在尝试添加新记录时(更新后),hibernate 抛出一个唯一的约束冲突异常。有什么理由说明为什么会这样吗?以上所有语句都在同一个事务中执行。
That's how Hibernate behaves by design, it will insert the values at save()time (A1, B1, C1) and then update them (C1 to C2), it won't insert A1, B1, C2). Quoting the King in Insert and Update in same flush:
这就是 Hibernate 的设计行为,它会在save()时间(A1、B1、C1)插入值,然后更新它们(C1 到 C2),它不会插入 A1、B1、C2)。在同一刷新中引用国王在插入和更新中:
Expected Hibernate behavior (we have debated whether this is really correct or not!) is that the INSERT statement will insert exactly the data that was set when save() was called. This gives the user a bit finer grained control, especially in a context where there are triggers etc. However, if you are not careful, it could perform badly.
预期的 Hibernate 行为(我们一直在争论这是否真的正确!)是 INSERT 语句将准确插入在调用 save() 时设置的数据。这为用户提供了更细粒度的控制,尤其是在有触发器等的上下文中。但是,如果您不小心,它可能会表现不佳。
Suggestion: delay the save to insert (A1, B1, C2) directly.
建议:延迟保存直接插入(A1,B1,C2)。

