I'm still not very clear about the way cascade works in deletion operations. I was wondering what happens if I have this:
class myBean{
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Cliente getClienteDiAppartenenza() {
return clienteDiAppartenenza;
}
}
class Cliente{
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
public List<myBean> getMyBeans() {
return myBeans;
}
}
if I delete the myBean with this property I'm not sure if the linked Cliente will be deleted too (weird in a manytoone) or the collection inside Cliente will be updated and that instance of myBean removed, then saved.
What will happen?? Hibernato docs aren't very clear about this...
This is not a Hibernate thing, this is part of the JPA 2.0 standard. You have two aspects in your annotations, one thing is the use of orphanRemoval.
You use orphanRemoval when the parent entity has control over the creation and destruction of the child entity. In UML this would be a case of composition that is a strong ownership and concident lifetime of the parts by the whole. The JPA 2.0 specification in section 2.9: Entity Relationships says:
A second aspect would be the use of cascase=REMOVE when no orphanRemoval is implied.
The section 3.2.3: Removal contains details about the remove process:
Your JPA provider isn't going to manage your java collections in memory for you. If you have a relationship mapped in both sides, then one side should be defined as the owning side using the mappedBy attribute in the mapping of the non-owning side. It's up to you to decide which side is the owning side. Once you've made that decision, the JPA provider will keep things up to date in the database using whatever cascade/orphan management you've defined in the mapping but you are left to manage your collections in the non-owning side.
One way to manage this is to have a service method that is used to make the change and that service method takes care of updating the collection or the reference in your 1-n and n-1 side of things so your java objects are correct in memory.