View RSS Feed

My Java Tips

one-to-many, sql

Rate this Entry
by , 06-02-2011 at 07:20 PM (2291 Views)
Let me presnet a simple <one-to-many> association from Parent to Child.

XML Code:
<set name="children">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>
Assume that we wish to execute the following code:

Java Code:
Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();
Hibernate would use two SQL statements for the above code. First one to insert record for c and second one for updating link from p to c. This will clearly violate any NOT NULL constraint on the parent_id column.

This can be fixed by specifying not-null="true" in the collection mapping. For example:

XML Code:
<set name="children">
<key column="parent_id" not-null="true"/>
<one-to-many class="Child"/>
</set>
But this is not a good solution. Now, i will present a better way of specifying one to many relation.

The problem is that the link from p to c is not considered part of the state of the Child object and is therefore not created in the INSERT. The solution is to make the
link part of the Child mapping. This is done as follows:

XML Code:
<many-to-one name="parent" column="parent_id" not-null="true"/>
Now we have to tell the collection not to update the link since the Child entity is managing the state of the link. We use
the inverse attribute.

XML Code:
<set name="children" inverse="true">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>
The following code would be used to add a new Child

Java Code:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();

Submit "one-to-many, sql" to Facebook Submit "one-to-many, sql" to Digg Submit "one-to-many, sql" to del.icio.us Submit "one-to-many, sql" to StumbleUpon Submit "one-to-many, sql" to Google

Tags: one-to-many Add / Edit Tags
Categories
Hibernate

Comments