I have a problem persisting two simple classes referencing each other in two independent unidirectional associations.
Here is what I do to create and persist my objects:
ClassA classA = new ClassA();
ClassB classB = new ClassB();
classA.setClassB(classB);
classB.setClassA(classA);
session.save(classA);
Cascading is set to "all" for both associations and the code seems to work except for the missing foreign key value in table CLASS_B. It is stored as NULL instead of using the ID of classA.
From what I understand the cascading persistence algorithm works as follows:
classA should be saved
classA has reference to classB
->classB has to be saved
->generate ID for classB
->store all classB properties
->classB instance is (ALMOST) stored in table CLASS_B
resume storing classA
generate ID for classA
store all classA properties (including ID pointing to classB)
classA instance is (COMPLETELY) stored in table CLASS_A
If the code actually works like this, I am not surprised that the foreign key in table CLASS_B is missing. At the time the classB instance is stored, the ID for classA hasnt been generated yet and is still NULL which is stored in the DB.
Are my assumptions correct and what can I do to get this working?
I am probably missing something important here, because the way I see it now the cascading algorithm is kinda useless.
Hibernate version: 2.1.8 or 3.0.3
Mapping documents:
<class name="ClassA" table="CLASS_A">
<id name="id" column="ID" type="int">
<generator class="native"/>
</id>
<version column="VERSION" name="version" type="int" unsaved-value="null"/>
<many-to-one name="classB" column="CLASS_B_ID" class="ClassB" cascade="all"/>
</class>
<class name="ClassB" table="CLASS_B">
<id name="id" column="ID" type="int">
<generator class="native"/>
</id>
<version column="VERSION" name="version" type="int" unsaved-value="null"/>
<many-to-one name="classA" column="CLASS_A_ID" class="ClassA" cascade="all"/>
</class>
Code between sessionFactory.openSession() and session.close():
ClassA classA = new ClassA();
ClassB classB = new ClassB();
classA.setClassB(classB);
classB.setClassA(classA);
session.save(classA);
Name and version of the database you are using: MySQL 4
|