3.2.5.ga
Hibernate Annotations : 3.3.0
I have a problem trying to add a new row in a one to many relationship.
I created a simple program to test this
A parent has multiple child. I retrieve only the parent using a HQL query.
Later I want to
add a new child without retrieving all the other child in the list. Is there any way I can add a new child without retrieveing all the other child associated with the parent. The issue I am having is I cannot create a new child and call a separate insert on this child.. Is failing on Backref
DAO methods
Code:
public Parent getParent(Long p) {
String queryString =
"from Parent p where " +
" p.parentId = :parentId" ;
Parent p1 = (Parent) getSessionFactory().getCurrentSession()
.createQuery(queryString).setParameter("parentId", p).uniqueResult();
return p1;
}
public void saveChild(Child c) {
getSessionFactory().getCurrentSession()
.save(c);
}
Parent ClassCode:
@Entity
@Table(name = "P_PARENT" )
public class Parent {
private Long parentId;
private Set<Child> child =new HashSet<Child>();
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="scenario_seq")
@SequenceGenerator(name="scenario_seq", sequenceName = "TEST_SCENARIO_SEQ")
@Column(name="PARENT_ID")
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
@OneToMany(cascade=CascadeType.ALL)
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@JoinColumn(name="PARENT_ID", nullable=false)
public Set<Child> getChild() {
return child;
}
public void setChild(Set<Child> child) {
this.child = child;
}
Child ClassCode:
@Entity
@Table(name = "P_CHILD" )
public class Child {
private Long parentId;
private Long childId;
private String description;
@Column(name="PARENT_ID", insertable=false, updatable=false, nullable=false)
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="scenario_seq")
@SequenceGenerator(name="scenario_seq", sequenceName = "TEST_SCENARIO_SEQ")
@Column(name="CHILD_ID")
public Long getChildId() {
return childId;
}
public void setChildId(Long childId) {
this.childId = childId;
}
ClientCode:
p1 = dao.getParent(13600l);
//This is what I want .. Create a new independent child and save it
Child c = new Child();
c.setParentId(1360l);
dao.saveChild(c);
But this fails with
Code:
Exception in thread "main" org.hibernate.PropertyValueException: not-null property references a null or transient value: com.fedex.ore.intl.domain.Child._childBackref
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
If I put this code it worksCode:
p1.getChild().add(c);
But it retrieves all the child associated to this parent which is a huge overhead.
Please let me know if there is a way to resolve this..
Thanks