How can I specify dependency in JPA without links from owner entity?
-
21-09-2019 - |
Question
The goal is to remove all Dependent when their Owner is deleted. I have the following classes:
@Entity
class Dependent {
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY, optional = false)
@Column(name = "OWNER")
private Owner _owner;
}
@Entity
class Owner {
...
}
In the current implementation Dependent still exist after its Owner has been deleted.
Owner doesn't have any links to Dependent and can't be changed, so I can't use @Dependent annotation or cascade=DELETE.
Does JPA support such "inverse dependency"? Another question is what does optional="false" guarantee while the field _owner is being deleted?
Solution
You have two options: You must either add a bag/set/list to the class Owner
with cascade-delete
. You can make this bag lazy and never access it, so it won't have a performance impact until you delete.
Your other option is to delete the Dependent
instances with a query when you delete the owner. Since JPA doesn't do automatic garbage collection of instances, you must start the delete manually anyway, so just make sure that every uses a single function to delete owners and then add the call to delete the children there.
OTHER TIPS
A way to resolve this problem is use a subclass which share the same tables as Owner's and add a collection which point to the Dependent. I'm not agree with Aaron Digulla's point on 'optional=false', this statement only shows the assocation is optional, and because you didn't have the bidrectional assocation, so the Dependent always handle the mapping.