1. No save-update cascade
In previous section, if you want to save the ‘Stock’ and its referenced ‘StockDailyRecord’ into database, you need to save both individually.
2. With save-update cascade
The cascade=”save-update” is declared in ‘stockDailyRecords’ to enable the save-update cascade effect.
The code session.save(stockDailyRecords); is no longer required, when you save the ‘Stock’, it will “cascade” the save operation to it’s referenced ‘stockDailyRecords’ and save both into database automatically.
Cascade delete example
In this example, if a ‘Stock’ is deleted, all its referenced ‘stockDailyRecords’ should be deleted from database as well.
1. No delete cascade
You need to loop all the ‘stockDailyRecords’ and delete it one by one.
2. With delete cascade
The cascade=”delete” is declared in ‘stockDailyRecords’ to enable the delete cascade effect. When you delete the ‘Stock’, all its reference ‘stockDailyRecords’ will be deleted automatically.
Cascade delete-orphan example
In above cascade delete option, if you delete a Stock , all its referenced ‘stockDailyRecords’ will be deleted from database as well. How about if you just want to delete two referenced ‘stockDailyRecords’ records? This is called orphan delete, see example…
1. No delete-orphan cascade
You need to delete the ‘stockDailyRecords’ one by one.
2. With delete-orphan cascade
The cascade=”delete-orphan” is declared in ‘stockDailyRecords’ to enable the delete orphan cascade effect. When you save or update the Stock, it will remove those ‘stockDailyRecords’ which already mark as removed.
In short, delete-orphan allow parent table to delete few records (delete orphan) in its child table.
How to enable cascade ?
The cascade is supported in both XML mapping file and annotation.
1. XML mapping file
In XML mapping file, declared the cascade keyword in your relationship variable.
In annotation, declared the CascadeType.SAVE_UPDATE (save, update) and CascadeType.REMOVE (delete) in @Cascade annotation.
Further study – Cascade – JPA & Hibernate annotation common mistake.