I am working on an application that uses EJB3 and JPA + Seam. In one of the screens in the application, I am creating new instances of a Parent object at run-time and also, creating new instances of Child objects. Following are the definitions (and mappings) of the two classes:
@Entity
public class Parent
{
@OneToMany(fetch=FetchType.LAZY, mappedBy="parent",
cascade={CascadeType.ALL}
private List<Child> children;
public void addChild(Child child)
{
this.children.add(child);
child.setParent(this);
}
public void removeChild (Child c)
{
this.children.remove(c);
c.setParent(null);
}
..
}
Here is the definition of the Child class (notice that Child has composite PK).
@Entity
@IdClass(ChildPK.class)
public clss Child
{
@Id
private Long key1;
@Id
private Long key2;
@Id
@Column(name="PARENT_ID")
private Long parentId;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="PARENT_ID", nullable=false, insertable=false, updatable=false)
private Parent parent;
...
}
The problem is when I hit the Submit button on the screen, I merge the detached Parent and its associated Children with the EJB tier and then eventually call flush(). In this case, on the flush() Hibernate runs the INSERT on the Parent object first and then, runs INSERT INTO CHILD object next. It fails throwing an ORA error saying: "Cannot insert NULL into "CHILD.PARENT_ID" column when executing the INSERT INTO CHILD statement.
In the GUI, when I create new Child objects, I call addChild() method on the Parent to store the children created. The addChild() method and removeChild() methods are really relationship management methods to manage this Parent-Child relationship.
|