Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 'Inverse' in mapping file

Can someone explain the use of inverse in the xml mapping file, I am reading the tutorial but failing to understand its use in the mapping file??

Thanks

like image 275
Noor Avatar asked Dec 16 '22 19:12

Noor


2 Answers

Inverse just decides which entity in a relationship is responsible for updating the database for reflecting the association.

Assume a one to many bidirectional association. There are two classes in the code A and B, A contains a set of B, B maintains a reference to A. At the database level, there is only one foreign key to be updated, the table for B contains a column to primary key of A.

In this case, assume we put the inverse = true on the set side. This implies that just adding an entity to the set will not fire the foreign key update. Because the respnsibility to update the foreign key rests with B. So, adding a B object to the set that A maintains is not enough to update the foreign key column. objectA.addToSetOfB(objectB) will not affect the foreign key.

Only when B is given a reference to A, will the foreign key in the table for B be updated. So, objectB.setA(objectA) will surely update the foreign key and actually setup the relationship.

I think the same concept will carry to the many to many relationships as well.

like image 91
Abhijeet Kashnia Avatar answered Dec 30 '22 23:12

Abhijeet Kashnia


If a collection is marked as "inverse", then Hibernate will not execute any SQL to maintain the collection in the database.

For example, one-to-many collections are often (in my experience, practically always) marked as inverse: the "many" entities (members of the collection) have a column with the parent's ID (mapped as a many-to-one property), and simply creating one of those entities means that it will be implicitly included in the collection, so no need to explicitly update them.

If using a many-to-many collection (which of course usually occur in pairs), one of the collections needs to be marked as "inverse", otherwise Hibernate will try to create the join table entries representing the collection twice.

like image 20
araqnid Avatar answered Dec 30 '22 22:12

araqnid