views:

177

answers:

2

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?

A: 

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.

Aaron Digulla
the Owner class cannot be modified.are you sure JPA doesn't provide an option to specify dependency in dependent class? so what is "optional='false'" for?
oakjumper
`optional=false` just declares which side is responsible for the mapping; you still need the mapping in both classes. If you can't change the owner class, you must use native queries and do everything manually. Don't forget to flush the caches every time.
Aaron Digulla
Your problem is "Owner class cannot be modified". This is the problem you must solve. You must decide whether it is more complex to change the owner class or spend a few weeks debugging the workaround. Or maybe you can map the owner class with a HBM file. If you're using Spring, you can easily mix annotations with the old XML config.
Aaron Digulla
A: 

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.

Cole