Hi All,
I’m working on a project that uses Hibernate as ORM layer. I’m currently facing a problem that Hibernate session.save() and session.update() doesn’t work with each other.
Here are the simplified classes structures:
Code:
class A{ //tableA has a column “record_id” which is primary key
Long recordId;
B b;
}
class B { //tableB has a column “record_id” which is primary key, but also a foreign key referencing tableA.record_id
A a;
}
Basically there is a one-to-one relationship between class A and B, but only class A has an ID attribute. Here is the hibernate configuration files:
A.hbm.xml
Code:
<id name=”recordId” column=”record_id”>
<generator class=”native”/>
</id>
<one-to-one name="b" class="B" cascade="all" lazy="false" />
B.hbm.xml
Code:
<id column=”record_id” type=”long”> // there is NO name=”recordId” property like in A.hbm.xml
<generator class=”foreign”>
<param name=”property”>a</param> //tableB.record_id references tableA.record_id
</generator>
</id>
<one-to-one name="a" class="A" cascade="none" constrained="true" lazy="no-proxy" />
Problem:
By the above configuration, I can save the data to both tables successfully by calling session.save(a), but session.update(a) will fail, because Hibernate always tries to insert new data into tableB even if there is already a row with the same record_id in tableB. (so hibernate can’t get the primary key for tableB).
I can fix this problem by adding the name=”recordId” property in B.hbm.xml and implementing getRecordId/setRecordId in B.class (by delegating the call to a.getRecordId/a.setRecordId), but this fix will then fail the session.save(a) with an unexpected update on tableB (Hibernate tries to update a row that doesn’t exist in tableB, in fact it should do an insertion) .
The embarrassment is that if I keep my fix, the session.save() won’t work, if I remove my fix, session.update() won’t work.
Any suggestions?
Thanks,
Jun