January 29, 2012

When is "inverse=true" and when it's not?



When I was a hibernate beginner, I was confused about deciding "inverse=true" or "inverse=false".

Here is an easy way to understanding it:

example scenario:
Person(one) <-> Address(many)
* bi-directional one-to-many relationship. (A person has multiple addresses.)

public class Person {
  private Integer id;
  private Set
addresses; // setter, getter Set
getAddresses() { return addresses; } .... }

public class Address {
  private Integer id;
  private Person person;

  // setter, getter
  Person getPerson() { return person; }
  .....
}
  • Person class has "Set
    getAddresses()" method
  • Address class has "Person getPerson()" method

If you think about the relation between two classes, it may gives an idea that person has addresses. (Person -> Addresses)
So, it feels like a person is an owner, and an address is a child. Then, you want to think that address is "inverse=true" because address is owned by person.
However, it's not correct.


Here, I'd like to suggest a way to think about it.

Let's look at table structure instead of classes.
  • PERSON[ id, name, ...]
  • ADDRESS[ idperson_id, city, street,...]

The person_id column in Address table is the relational information between thease two tables.
So, Address is an owner of the relationship, and Person is the inverse side.
"inverse=true" means "this side is the inverse side", and "inverse=false" means "this is not the inverse side. this side is the owner of the relationship".


Answer is:

  ...
  inverse="true">
    
    
  



  ...
  



In sum, look at the table structure to distinguish "inverse=true" or "inverse=false".
If the table has relational information, then it is the owner side. So, it's not inverse side.(inverse=false)
If the table doesn't have relational information, then it is the inverse side. So, it needs "inverse=true".


No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts