Java – hibernate cascades many relationships

Dormant novice I have two tables a and B, which have a many to many relationship defined by table AB (a_id and b_id), in which the foreign key refers to A.A_ ID and B.B_ ID, and cascades when defined is deleted and updated

I have a mapping

a.hbm. XML has

<set name="bSet" table="AB" inverse="true" lazy="false" fetch="select" cascade="all">
    <key>
        <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);

Send a object from the front end as a JSON of a set with B, and table a is correctly updated when AB is not touched

Can anyone point out what's wrong with me? This is JSON

{
    "a_field1": "value1","a_field2": "value2","aId": 1,"bSet": [
        {
            "bId": 100
        },{
            "bId": 200
        }
   ],"a_field3": "value3"
}

Initially, DB set 3 records in the AB table

(1,100) 
(1,200) 
(1,300)

The end result in the database should be

(1,200)

The last line (1300) should be deleted

Any help is greatly appreciated

>Shah

Solution

My best guess (you didn't provide any examples of server code that handles requests) is that you update only one side of the bidirectional association In other words, you just deserialize the a instance and merge it If you get a new a, you still need to merge a instances, but you also need to load all B instances that a no longer references, delete a instances from the list, find all B newly referenced by a, and add a to its list. This is one of the dangers of two-way relationship in the code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>