Friday, October 30, 2009

Notes on Bidirectional Associations in Hibernate Collection Mapping

The Hibernate collection mapping

Bidirectional associations

The example uses Customer and Address. There is a one to many relationship from customer to address. My tests results are the follows.
I made a new Customer object and a new Address object. A customer java object has a set of Address object. I add the new Address object to the set. Notice that no id value is specified for Customer and Address. Hibernate will generate them when the objects are saved.
  1. The inverse="true" can only be declared on the many-valued end. ( Customer in this case). If you declare it in the Address mapping file, error occurs.
  2. If you do not declare inverse="true", you’ll get error when saving the Customer object. The error will say that the object is transient. ( It is the Address object in this case.)
  3. If you use inverse="true" but cascade="none", you can save the Customer, but the address is not saved to the address table
  4. If you use inverse="true" and cascade="save-update", the both the customer and address will be saved to the tables successfully.
Note that #4 is consistent with the Hibernate documentation about the many-to-many association. In the many-to-many association, Changes made only to the inverse end of the association are not persisted. In our one-to-many association, the inverse end is the many-valued end, which is Address.

Some other observations.
In cascade="all", "all" does not include everything. "delete-orphan" is separate. So you can see cases like cascade="all,delete-orphan" or "all-delete-orphan", ( I think they are the same).

No comments:

Post a Comment