I've already read documentation, FAQs and previous postings.
However, I've not found this one.
I have a parent-child relationship between two tables, the
foreign table has a composite key which includes the
foreign key to the primary table.
I have a problem while trying to save in cascade. Reads
and deletions work fine. I've found a workaround ( which
I describe later ), but I'd like to know if there's a better way
to to this ).
The schema may not be changed and is like the following:
-- primary table
CREATE TABLE curriculum ( cu_id INT PRIMARY KEY, ... );
-- foreign table
CREATE TABLE topic ( cu_id INT NOT NULL, to_id INT NOT NULL, ...
PRIMARY KEY ( cu_id, to_id ), FOREIGN KEY ( cu_id ) REFERENCES curriculum, );
My mappings look like the following:
For the primary table:
<class table="curriculum" name="com.acsinet_solutions.curri.data.CurriculumDTO">
<id name="id" type="int" column="cu_id"> <generator class="identity"/> </id>
<set name="topics" inverse="true" cascade="all-delete-orphan" lazy="true" sort="natural"> <key column="cu_id"/> <one-to-many class="com.acsinet_solutions.curri.data.TopicDTO"/> </set>
</class>
For the foreign table:
<class table="topic" name="com.acsinet_solutions.curri.data.TopicDTO">
<composite-id name="key" class="com.acsinet_solutions.curri.data.Key">
<key-property name="id" type="int" column="cu_id"/> <key-property name="number" type="int" column="to_id"/>
</composite-id>
<many-to-one name="curriculum" not-null="true" insert="false" update="false" class="com.acsinet_solutions.curri.data.CurriculumDTO"> <column name="cu_id"/> </many-to-one>
</class>
TopicDTO implements Lifecycle, an interceptor is properly configured
for the session factory, and the key class implements equals() and
hashTable() accordingly.
The problem is that when a save() is tried to be executed, Hibernate
does not automatically set the id property of the Key class, so the
INSERT method is not performed correctly.
The workaround I've found to solve this is to explicitly set the
property as part of the onSave() method:
// snippet of TopicDTO
public boolean onSave( Session arg0 ) throws CallbackException {
// here I explicitly set the id field of the Key class
getKey().setId( _curriculum.getId() );
_saved = true;
return false; }
Doing this everything works, but I think this is something the
framework should do for me, so I don't have to explicitly set
the key for every foreign object I have with composite keys
managed this way ( which is VERY common in the type of
projects I work in ).
Maybe I'm missing something in my mappings, I hope someone
could give me a hint.
I've tested this with Hibernate 2.0 and 2.1b6; same results.
- thanks in advance
Santiago
|