In an application using hibernate 5.0.9 have nested parent child relation where parent is relation owner respresented as below.

Tables: -

ParentEntity
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id")
@OrderBy("listOrder ASC, dateCreated ASC")
private Set<ChildEntity> childCollection;

ChildEntity
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "child_id")
@OrderBy("col_id ASC, list_order ASC")
private Set<GrandChildEntity> grandChildCollection;

GrandChildEntity

I want to update childs and grandChilds of a parent as follows :-

Read the existing parent from DB and get set of all childs and its grandchilds. Move existing grandChild from one child to another, so the requirement is only reference of child for a grandChild has to be updated other than that all columns in DB for grandChild has to be untouched.

I am trying to use hibernate merge by to perform this operation but it is throwing me exception :

deleted object would be re-saved by cascade (remove deleted object from associations)

How I can remove grandchild from existing child collection and attach to other child collection in a single transaction??

1

There are 1 best solutions below

0
On

I assume this is not the exact same mapping that you use in your app? Are you also using orphanRemoval? I don't think that orphan removal across multiple associations works, so moving the entity from one to-many association to another will still mark the entity as orphan. Remove the orphan removal configuration and instead remove the entities manually when you are sure that an entity should actually be removed.

Apart from that, I would also suggest you make the association bidirectional and use mappedBy on the many-side. so that the FK column side drives the association instead, which enables you to "move" objects by changing their parents. It also makes no sense to use @OrderBy on associations that use a Set. Just remove that annotation.