In this tutorial we are going to differentiate between the cascade option and inverse keyword.
Cascade : In Hibernate the cascade option is used for defining the Owner in the relationship between the associated objects. It is an optional attribute that may be used to specify that which operation should be cascaded. Cascade has the various options "all ", " save | update | delete | merge " that may be used with either of the single option or may be used with the multiple options. Cascade decides the same operation done on the parent object is done on the associated object at the same time. A keyword "cascade" is generally used when there is a mapping does for the collection to handle the state of collection automatically.
NOTE : When you will use the cascade with 'all' option it means the owner class has all the manipulation facility that it can apply on the relationship from the parent object to the associated object.
Example of Cascade :
A mapping file that contains the mapping of collection mapping of the cascade attribute will be as follows :
<set name="goodsRecords" cascade="all" table="goods_record"> <key> <column name="goodsId" not-null="true" /> </key> <one-to-many class="roseindia.GoodsRecord" /> </set>
Inverse : In Hibernate an inverse keyword is used in the hibernate mapping file for maintaining the relationship of the parent and the associated child object. This keyword is responsible for managing the insert / update of the foreign key column. An inverse keyword has the boolean value "true/false". Default value of this keyword is 'false' it means the parent class is responsible for saving/updating the child and it's relationship. And when the keyword inverse is set to the 'true' it means an associated subclass is responsible for saving/updating itself.
NOTE : An inverse keyword is always used with the one-to-many and many-to-many. It doesn't work with many-to-one relationship.
A hibernate mapping file into which the inverse keyword is used as :
<set name="goodsRecords" inverse="true" table="goods_record"> <key> <column name="goodsId" not-null="true" /> </key> <one-to-many class="roseindia.GoodsRecord" /> </set>
The relationship will be converted in owner to owned or vice-versa when you will use the inverse keyword with the following boolean value :
if inverse = "true" : In such case according to the above given example goods_record will be acted as owner and the goods2 will not be updated.
if inverse = "false" : In Hibernate the default value of inverse attribute is set to 'flase' in such case according to the above given example goods2 is the owner and it will update the relationship.
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Difference Between cascade and inverse Keyword
Post your Comment