Hibernate和NonUniqueObjectException [英] Hibernate and NonUniqueObjectException

查看:135
本文介绍了Hibernate和NonUniqueObjectException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体,其中包含两个具有@ManyToOne关系的实体。

i have an entity that contains two other entities with @ManyToOne relationship.

@Entity
public class A extends Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private B b;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private C c;

}

如果我尝试保存一个具有B_ID的A实例和另一个A记录的C_ID我得到例外:

If i try to save an A instance that have "B_ID" and "C_ID" of another A record i get the exception:

org.hibernate.NonUniqueObjectException:具有相同标识符值的不同对象已经与会话

例如:

A table
|   ID  |   B_ID    |   C_ID    |
|    1  |      1    |   null    |    // this works
|    2  |   null    |      1    |    // this works
|    3  |      1    |      x    |    // this throws the exception
|    4  |      x    |      1    |    // this throws the exception

x=any value of existent B/C_ID 

B_ID和C_ID在我的模型中不是唯一的,(B_ID + C_ID)不是唯一的限制!

我可以做什么?

提前感谢

推荐答案

Hibernate并不抱怨数据库这里的唯一性,它抱怨当前的会话已经包含一个与要保存的新对象具有相同ID的对象。它不会允许这一点 - Hibernate严格要求给定的ID不能由单个会话范围内的两个不同对象表示。

Hibernate is not complaining about database uniqueness here, it's complaining that the current Session already contains an object with the same ID as a new object that you're trying to save. It won't permit this - Hibernate has a strict requirement that a given ID cannot be represented by two different objects in the scope of a single session.

在某些时候,您的应用程序已保存dor加载了具有相同ID的实体,该对象已经与会话注册。在这个具体情况下,很难说出这个ID,因为异常文本不清楚。尝试暂时删除级联指令,看看它是否仍然发生,尝试缩小。

At some point, your application has save dor loaded an entity with that same ID, and that object is already "registered" with the session. It's hard to tell in this specific case which ID it's complaining about, since the exception text isn't clear. Try temporarily removing the cascade directives and see if it still happens, try to it narrow down.

如有必要,您可以强制会话对于给定的ID(使用 Session.evict(),或JPA 2.0 API中的 EntityManager.detach()),但这不是一个非常优雅的解决方案。

If necessary, you can force the session to "forget" about any existing objects for a given ID (using Session.evict() in the Hibernate API, or EntityManager.detach() in the JPA 2.0 API), but that's not a very elegant solution.

要重申 - 这个异常与数据库约束完全没有关系,它是关于Hibernate保护其内部内存状态的一致性。

To reiterate - this exception has nothing at all to do with the database constraints, it's about Hibernate protecting the consistency of its internal in-memory state.

这篇关于Hibernate和NonUniqueObjectException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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