Sunday, October 2, 2016

Cascade and Inverse in Hibernate

In case of many-to-many relationship via intermediary table, CASCADE says whether a record will be
created/updated in the child table and INVERSE says whether a record will be created/updated in the
intermediary table

Example:
One student can have multiple phones, so Student class has property for Set of phones.
One Phone can be owned by multiple students, so Phone class has property for Set of Students.

This mapping is maintained in STUD_PHONE table.

So there are three tables -> STUDENT, PHONE and STUD_PHONE (intermediary) table.

Mapping might look like:

<set name="phoneset" table="stud_phone" cascade="save-update" inverse="true">
  <key column="mapping_stud_id">< /key>
  <many-to-many class="com.domain.Phone" column="mapping_phon_id"/>
</set> 

A new student object is created and 2 new phone objects are added to its set.
Now after calling session.save(student_obj) , depending upon CASCADE and INVERSE settings different queries will be fired.

Below are the different combinations->

1) CASCADE IS NONE and INVERSE is false

insert into STUDENT (Name, stud_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)

2) CASCADE is NONE and INVERSE is true

insert into STUDENT (Name, stud_id) values (?, ?)

3) CASCADE is save-update and INVERSE is false

insert into STUDENT (Name, stud_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)

4) CASCADE is save-update and INVERSE true

insert into STUDENT (Name, stud_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)

Thus only when CASCADE was save-update the records were created in PHONE table, otherwise not.

When INVERSE is false (Student is the owner of relationship) the intermediary table STUD_PHONE was updated.

When INVERSE  is true (Phone is owner of relationship), so even though a new student was created, the intermediary table was not updated.

So in case of relation of two entities, CASCADE affects other entity table and INVERSE  affects intermediary table. So their effect is independent.

No comments:

Post a Comment

Home