开发者

Hibernate OneToMany generated foreign key

I have the following table structure:

parent(parentId)
child(childId, parentId fk)

Then, I have the following objects:

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

   @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinColumn(name = "parentId")
   S开发者_开发问答et<Child> children
}

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

   @Column(...)
   private String parentId;

}

Now, I create a transient parent and child, and I add the child to the parent, then save the parent:

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

parentDao.save(parent);

I get the exception:

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

My question: How can I get the parentId in the child class to automatically be set to the value generated by the insertion of the parent?


I would re-arange your class structure as follows:

@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;

}

Then when hibernate fetches the parent class, and initializes the set of children, the child class will have a reference to the parent class. Then to get the parentId, you would call:

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


Your child shouldn't have a private String parentId, but a private Parent parent, and when you parent.children.add(child), you must also child.setParent(parent). See the prototypical parent-child relationship example in the Hibernate reference and the bidi one-to-many section of the annotation reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜