hibernate many to many relations cascade
Newbie to hibernate i have two tables A and B that have many to many relations defined by a table AB(A_ID and B_ID) with foreign key reference to A.A_ID and B.B_ID and cascade on delete and update defined.
I have mapped
a.hbm.xml has
<set name="bSet" table="AB" inverse="true" lazy="false" fetch="select" cascade="all">
<key>
&开发者_JAVA技巧lt;column name="A_ID" not-null="true" />
</key>
<many-to-many class="objectB" >
<column name="B_ID" not-null="true" />
</many-to-many>
</set>
b.hbm.xml has
<set name="aSet" table="AB" inverse="false" lazy="false" fetch="select" cascade="all">
<key>
<column name="B_ID" not-null="true" />
</key>
<many-to-many class="objectA">
<column name="A_ID" not-null="true" />
</many-to-many>
</set>
//ObjectA.java has
private Set<ObjectB> bSet = new HashSet<objectB>(0);
//ObjectB.java has
private Set<ObjectA> aSet = new HashSet<objectA>(0);
From the front end sends the A object as a json with set of B's the table A is getting updated correctly while the AB is untouched.
Can someone point out where am I going wrong? Here is the JSON
{
"a_field1": "value1",
"a_field2": "value2",
"aId": 1,
"bSet": [
{
"bId": 100
},
{
"bId": 200
}
],
"a_field3": "value3"
}
initially the db is set up with 3 records in AB table
(1,100)
(1,200)
(1,300)
The final results in the db should have been
(1,100)
(1,200)
the last row (1,300) should have been deleted.
Any help is greatly appreciated.
- Shah
My best guess (you don't provide any example of the server code that handles the request) is that you're only updating one side of the bidirectional association. In other words you're just deserializing that A instance and doing a merge. If you get a new A you still need to merge the A instance but you also need to load up all the B's that A no longer references and remove the A instance from their list and also look up all the B's that are newly referenced by A and add A to their list. It's one of the hazards of a bidirectional relationship in code.
精彩评论