I have a simple object relation, I wish to persist with hibernate.
Basically, its a Parent which contains a collection of Children. All I wish to do, is load the parent if it exists, otherwise create it, add elements to it and save it.
This is being done in a GWT enviroment, so I pass a ChildDTO to this method, which is basically just a non-persistant version of the Child class (which is incompatible with gwts RPC serialization).
public Integer testHibernate(Integer parentId, ChildDTO[] test) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Parent model;
if(parentId == null) {
// if the parentId is null, create new instance
model = new Parent );
}
else {
model = (Parent) hib.load(Parent.class, dto.getId());
}
model.setName("dummy name");
for(int i = 0; i < test.length) {
model.addChild(new Child(test[i].getId(), test[i].getName()));
}
hib.save(model);
hib.getTransaction().commit();
return model.getId();
}
Right, this works fine for creating new Parents, without children. It also works fine if i am just adding one child to an existing parent. However, if i add more than one child, i get a “could not insert” error from hibernate.
Also, if I try adding just one child, to a already existing parent, which already have one child added. I get a “a different object with the same identifier value was already associated with the session” error.
Additional question. When inserting just one child, on a empty parent, hibernate does the following:
Hibernate: insert into Child(ChildId, ChildName) values (default, ?)
Hibernate: update Parent set ChildId=? where ChildId=?
Whats with the update? :S
From the question it seems that the Parent-Child relationship has been setup as one-to-one rather than one-to-many. First make sure that is correct in your hibernate config file.
In the following code snippet, you just save the child with the Id without checking if it already exists. Remember that
Childis also stored in database as a row. So you need to check if that object exists in database.That is logical, the first
INSERTstatement corresponds to the new row for theChildobject. The secondUPDATEstatement corresponds to establishing the link betweenParentandChildobjects.You could optimize this by setting up
inverserelation. In this scenario, theChildtable stores the parent_id and therefore results in oneINSERTstatement than two statements.Refer to this link in Hibernate documentation which clearly explains on how to setup and implement the
Parent-Childrelationship: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-parentchild.html#example-parentchild-bidir