Bi-directional Relationships
Many of the relationships you will wish to model using Hibernate will be bi-directional. For example, given an author, you will wish to know the posts written by that author, and given a post, you will wish to know the author. As you use the various collection tags to model these bi-directional relationships, you will encounter one of the more confusing aspects of Hibernate: the inverse attribute.
Simply put, inverse="false" defines the side of a bi-directional relationship responsible for maintaining the association. The collection mapping with the inverse="false" attribute (the default value) is responsible for the appropriate SQL query (INSERT, UPDATE, or DELETE). If the inverse="false" attribute is set on a one-to-many relationship, the column of the target will be updated. If inverse="false" is set on a many-to-many association, the association table will be updated.
Conversely, Hibernates ignores changes made to the association set to inverse="true".
This can be somewhat confusing, but once you understand that the inverse="false" side is responsible for managing a relationship, there are just a few simple guidelines to follow.
If you are using a one-to-many/many-to-one bi-directional relationship, the many-to-one side will be responsible for managing the relationship (and therefore the one-to-many side should be set to inverse="true"). For example, in the example shown in Chapter 2, the Author side of the bi-directional relationship is set to inverse="true". This means that Hibernate ignores changes to the Author object's set of posts. For performance reasons, this is virtually always the correct model.
The choice of inverse="true" and inverse="false" is really only complex in a bi-directional many-to-many relationship (i.e., when Hibernate handles a collection table is handled under the covers). In this situation, the rule of thumb is that inverse="false" should be set for the side of the relationship with the smallest number of elements changed the most frequently. For example, consider the relationship shown in Figure 7.4.

Assuming that the list of beverages (i.e., the Beverage table) is relatively small and static, but that the customers are numerous and place many orders, you should model this many-to-many relationship by setting the mapping of the Beverage collection to inverse="true" and the Customer side to inverse="false".
 |