Inverse defines which side is responsible of the association maintenance. The side having inverse="false" (default value) has this responsibility (and will create the appropriate SQL query - insert, update or delete). Changes made to the association on the side of the inverse="true" are not persisted in DB.
Inverse attribute is not related in any way to the navigation through relationship. It is related to the way hibernate generate SQL queries to update association data. Association data are:
a column in the one-to-many association
a row in the association table in a many-to-many association
Monodirectional association is managed by the only side available through navigation. When association is bidirectional, choosing the manager side allow better SQL optimization, this is the recommended behaviour
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<Address> addresses;
// setter, getter
Set<Address> 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
Let's look at table structure instead of classes.
• PERSON[ id, name, ...]
• ADDRESS[ id, person_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".
<class name="Person">
<id name="id">...</id>
<set name="addresses" inverse="true">
<key column="person_id"/>
<one-to-many class="Address"/>
</set>
</class>
<class name="Address">
<id name="id">...</id>
<many-to-one name="person" class="Person" />
</class>
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".
In Hibernate, only the relationship owner should maintain the relationship, and the “inverse” keyword is created to defines which side is the owner to maintain the relationship. However the “inverse” keyword itself is not verbose enough, I would suggest change the keyword to “relationship_owner”. The inverse=”true” means this is the relationship owner, whereas inverse=”false” (default) means it’s not.
0 comments:
Post a Comment