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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With