Reputation: 57
I've read about jpa cascade but still have a question.
ParentBiz.java
...
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent", fetch = FetchType.LAZY, targetEntity = ChildrenBiz.class)
private List<Child> children;
...
Child.java
...
@ManyToOne(targetEntity = ParentBiz.class, fetch = FetchType.LAZY)
@JoinColumn(name = "ID_PARENT", nullable = false)
@ForeignKey(name = "FKMAW53A")
private Parent parent;
...
Simple, right? I've wrote a test inserting a parent (and its children, by cascade) and it works ok. Then I add a child on parent and merge the parent, and it works ok too. But when I remove a child and merge the parent, it's not cascading.
As far as I know, it should remove all children and insert it again every time I merge the parent, but that's not what is happening. I'm really clueless, cause it seems easy...
Upvotes: 0
Views: 239
Reputation: 21145
It cannot cascade the merge request to the child because it is not in the Parent's children collection to cascade to. So the provider cannot see any changes made to children not in the list. Because the child owns the relationship, it cannot be changed from the parents side, and the relationship will continue to exist in the database.
If you want the child to be removed from the database, you will need to use orphan removal. This will cause any elements removed from the collection to be deleted from the database. But there should be no other references to the child, and its not a great measure to take if these child entities are meant to be independent from their parents or can be swapped around.
Another solution is to explicitly merge children once they are removed from their parents. If that is not possible, you might change the relationship to be unidirectional and go from the parent to the child. This will allow the parent to control the foreign key, so that changes to the collection cause the changes to be reflected in the database.
Upvotes: 1