Using inverse true in hibernate

Viewed 31519

I am going through the hibernate documentation and came across the concept of inverse attribute. I am new to Hibernate so I am feeling difficulty in understanding the concept properly.

http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/collections.html#collections-bidirectional

<class name="Category">
    <id name="id" column="CATEGORY_ID"/>
    ...
    <bag name="items" table="CATEGORY_ITEM">
        <key column="CATEGORY_ID"/>
        <many-to-many class="Item" column="ITEM_ID"/>
    </bag>
</class>

<class name="Item">
    <id name="id" column="ITEM_ID"/>
    ...

    <!-- inverse end -->
    <bag name="categories" table="CATEGORY_ITEM" inverse="true">
        <key column="ITEM_ID"/>
        <many-to-many class="Category" column="CATEGORY_ID"/>
    </bag>
</class>

From above code, the inverse="true" is applied to categories, so I understood that categories is the inverse end.

But I am seeing some contradiction to my understanding:

Changes made only to the inverse end of the association are not persisted.

category.getItems().add(item);   // The category now "knows" about the relationship
item.getCategories().add(category); // The item now "knows" about the relationship

session.persist(item);   // The relationship won't be saved!
session.persist(category);   // The relationship will be saved

If categories is on inverse end then how the relationship is saved here?

The non-inverse side is used to save the in-memory representation to the database.

After looking at the example and reading above statement I came to know that categories is on non-inverse end.

Please help me in knowing how to interpret this inverse="true" attribute. After searching in net and looking at answers in SO, I came to know the usefulness of this attribute but still I have this confusion.

2 Answers
Related