I supposed the following
Code:
@Entity
private class Parent {
@Id
@GeneratedValue(GenerationType.AUTO)
@Column(name="PARENT_ID")
private Integer id;
// Notice mappedBy attribute's value refers Parent property OR field in Child class
@OneToMany(
mappedBy="parent",
cascade={
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinColumn(name="PARENT_ID", nullable=false)
private List<Child> childList = new ArrayList<Child>();
public void addChild(Child child) {
childList.add(child);
// It is important because mappedBy="parent"
child.setParent(this);
}
}
@Entity
public class Child {
@Id
@GeneratedValue(GenerationType.AUTO)
@Column(name="CHILD_ID")
private Integer id;
@ManyToOne
@JoinColumn(name="PARENT_ID", nullable=false)
private Parent parent;
}
So you should use the following
Persist
Code:
Parent parent = new Parent();
parent.addChild(new Child());
parent.addChild(new Child());
session.save(parent); // Both parent and childs will be saved
Update
Code:
Parent parent = new Parent();
Child updatableChild; // Notice child id should be set up
parent.addChild(updatableChild);
session.save(parent); // Parent will be saved and Child will be updatable
I hope it helps you
Regards,
Arthur Ronald F D Garcia (Java programmer)
Natal/RN (Brazil)