Il mapping in file hbm è un’attività che non faccio spesso, ma quando la faccio mi scordo sempre se e come usare l’attributo “inverse” nelle collection.

A futura memoria segnalo questo post  di Brian Chavez che mi sembra più esauriente della documentazione ufficiale di NH.

Suppose you have ParentTable (parentId PK, parentcol1, parentcol2) and ChildTable(childid PK, parentid FK, childcol1, childcol2).  In a one-to-many relationship, you will have one parent and many children.  The ChildTable has a primary key and foreign key.   The foreign key is a reference to the primary key in the ParentTable.  If you look at the ChildTable, you will notice that the ChildTable stores extra information about a row in the ParentTable via the ChildTable's parentId foreign key.  Using this perspective, the "child" owns (knows about) the relationship it has with its parent row.  So, the child will be the owner of the relationship in this one-to-many relationship.

Quindi “the child will be the owner of the relationship in this one-to-many relationship” e di conseguenza, siccome il parent non è l’owner della relazione, è considerato l’inverso (il “target”).

In Hibernate, you might encounter the inverse="true" attribute being used in the definition of a bidirectional relationship. If so, don't worry, because this feature is equivalent to ... the non-owner of the relationship whose table doesn't have the foreign key. Similarly, the Hibernate inverse="false" attribute is equivalent to the ... owner of the relationship whose table has the foreign key.

La cosa più importante è che

[…] a Hibernate mapping with inverse="true" set on the many-to-one side of a bidirectional relationship. If you find such a mapping, you should change it ..., as it is not a best practice in Hibernate and does not generate optimal SQL. For instance, if the many-to-one side is set to inverse="true" then every time you create a child, Hibernate will execute two SQL statements, one to create the child and one to update the child with the foreign key of the parent.

hth

Technorati Tag: