【问题标题】:Hibernate @ManyToOne annotation creating only the child referencing existing parent tableHibernate @ManyToOne 注释仅创建引用现有父表的子表
【发布时间】:2013-07-06 09:25:53
【问题描述】:

我目前正在处理一个我必须使用多对一关系的项目。我想从数据库中的现有表中检索父级并映射到一个新的子对象。但是每次我这样做时它都会失败,而是尝试再次创建父级。这里是变量声明:

@Entity @Table (name= "children")
public class Child implements Serializable{
@ManyToOne (fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST})
@JoinColumn (name = "parent_id",referencedColumnName = "id")
private Parent parent;
}

每次我创建一个新的子记录时,它都会尝试使用我从数据库中提取的现有父级的数据创建一个新的父级,从而导致此错误:

duplicate key value violates unique constraint "parents_parent_name_key"
Detail: Key (parent_name)=(Jimmy) already exists.

Batch entry 0 insert into parents(parent_name, id) values ('Jimmy', '13')     was
aborted.  Call getNextException to see the cause.

如果我尝试重做,我会得到一个不同的错误:

org.hibernate.PersistentObjectException: detached entity passed to persist:
com.house.entity.Parent

谢谢你

【问题讨论】:

    标签: hibernate postgresql nhibernate jpa


    【解决方案1】:

    我能够修复它。问题是我对两个表和其他表使用了一个序列。如果您的实体之间有多个关系,并且您希望在一个实例中跨它们保留数据,请不要这样做。当我改变它时,它工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 2011-08-05
      • 2017-07-31
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多