Hello all,
Hibernate version: 3.1.3
I have a Parent class that has one-to-many relationship with a Child. I've read the Hibernate document about setting up Parent / Child relationship and code them accordingly, i.e.:
1. In Child.hbm.xml, I put this:
Code:
<many-to-one name="parent" class="Parent" column="parent_id" not-null="true" />
Respectively, in Child.java, I put:
Code:
private Parent parent;
// getter and setter here
2. In Parent.hbm.xml, I put this:
Code:
<set name="children" lazy="false" inverse="true" cascade="all-delete-orphan">
<key column="parent_id" not-null="true"/>
<one-to-many class="Parent"/>
</set>
In Parent.java I have:
Code:
private Set<Child> children;
and:
Code:
public Set<Child> getChildren()
{
return this.children;
}
public void setChildren( Set<Child> children)
{
this.children = children;
}
Now, my question is this:
I get Parent from DB, and then I populate an ActionForm with the Parent. I send ActionForm to JSP and let the user modify it as necessary, adding/updating/removing children as needed.
When the user submits, I use the ActionForm to populate back a new empty Parent (the ids are kept throughout even in JSPs as hidden inputs). Here's where the problem starts. I can modify a Child, no problem. But I can't delete a Child from Parent's children Set and having it persisted to the database.
Now, before you ask me to RTFM ;-), I am also aware of this:
Code:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
session.delete(c);
session.flush();
However, we've put an abstraction layer between domain models and the data access mechanism, so we don't usually get the Hibernate Session instance directly. The flow for everything else works nicely, that is:
1. Get a model instance from DB
2. Update in UI
3. Go back to biz layer
4. save back the modified model instance to DB (eventually gets to Hibernate's saveOrUpdate());
Is there a common idiom or pattern to handle this? Is there any way of me telling Hibernate that, yes, child A has just been removed from UI, please remove it from DB as well, without breaking the established flow? As it is now I can only persist updates to children, but not children removal (Hibernate only generates UPDATE statement for any children that are left, it still doesn't touch the ones that are supposed to be removed from the DB). That is, if Parent has child A, B, C, D, then D is removed in the UI layer, instead of generating:
DELETE from CHILD where id = <D's id>
and UPDATE A, B, C
It merely generates UPDATE A, B, C, and leaves D untouched.
How do you guys usually do it? I'm sure there's a common idiom for this? I'm using Spring if that will help...
Thank you very much,
Ray