Hibernate OneToMany生成了外键

时间:2011-08-04 19:29:09

标签: java hibernate

我有以下表结构:

parent(parentId)
child(childId, parentId fk)

然后,我有以下对象:

@Entity
@Table(name = "parent")
public class Parent {
   @Id
   @GeneratedValue(...)
   private String id;

   @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinColumn(name = "parentId")
   Set<Child> children
}

@Entity
@Table(name = "child")
public class Child {
   @Id
   @GeneratedValue(...)
   private String id;

   @Column(...)
   private String parentId;

}

现在,我创建了一个临时的父和子,并将子项添加到父项,然后保存父项:

Parent parent = new Parent();
parent.children.add(new Child());

parentDao.save(parent);

我得到例外:

org.hibernate.PropertyValueException: not-null property references a null or transient value

我的问题:如何让子类中的parentId自动设置为插入父级所生成的值?

2 个答案:

答案 0 :(得分:3)

我会按如下方式重新排列你的类结构:

@Entity
@Table(name = "parent")
public class Parent {
   @Id
   @GeneratedValue(...)
   private String id;

   @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinColumn(name = "parentId")
   Set<Child> children
}

@Entity
@Table(name = "child")
public class Child {
   @Id
   @GeneratedValue(...)
   private String id;

   @Column(...)
   private Parent parent;

}

然后当hibernate获取父类并初始化子集时,子类将具有对父类的引用。然后要获取parentId,您可以调用:

Child c = new Child()....
c.parent.id;

答案 1 :(得分:1)

您的孩子不应该有private String parentId,而是private Parent parent,当您parent.children.add(child)时,您还必须child.setParent(parent)。请参阅Hibernate参考中的prototypical parent-child relationship example和注释参考的bidi one-to-many section