Lets say I have two tables - "child" and "parent" with many-to-one relation. What I need is to delete child entries if parent record is deleted.
It is not a problem if I link child table from parent by creating one-to-many association in parent.hbm and set cascade="all-delete-orphan".
The problem is I don't want one-to-many relation on the parent side, so I created many-to-one on the child side. The reason for that is child table is pretty big and I don't want to extract hundreds of records every time I use parent. So my configuration looks like this:
child.hbm:
<many-to-one name="parent" class="com.example.Parent" column="parentid"/>
while parent.hbm has no associations with child.
The question is: How to make Hibernate delete records from child table when deleting a parent if a child is linked to a parent with many-to-one?
Thanks.
Couple of options:
add the one-to-many to the parent with cascading delete, but mitigate the performance loss using lazy loading.
use a Hibernate Interceptor (or an aspect in an AOP environment) to detect parent record deletions and delete children.
Personally I would favour the first option, as it lets your data model more closely reflect the real relationships in your data.
Edit: there's a third option, but it's not pleasant - use a database trigger, and flush your Hibernate cache (or use a non-caching session).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With