0

I have 2 Entities (Parent and Child) that have a OneToMany relation between them.

The Parent has List of Child and the Child has Parent field.

The Child has

 @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})

in the Parent field.

The Parent has

@OneToMany(mappedBy="parent", cascade = CascadeType.ALL, orphanRemoval = true)

in the Child list.

I want to find a way to replace the Parent of one child with another Parent. (i.e. change the Parent of ChildA from ParentA to ParentB)

Because I want to follow the Parent list I want to remove the child from the list. The problem is that even if I first add ChildA to ParentB's list, set the Parent field of ChildA to ParentB and only after that remove it from ParentA's Child list, for somehow it completely deletes the Child (apparently because of the OrphanRemoval)

How can I make this swap without changing the configuration of the hibernate and with a removal from ParentA's list(OrphanRemoval etc.)?


EDIT

I prefer to avoid using entityManager.flush()

Dvir
  • 301
  • 1
  • 2
  • 16
  • probably helpful to understand the inner working: https://stackoverflow.com/questions/34004855/prevent-hibernate-from-deleting-orphaned-entities-while-merging-an-entity-having – Zeromus Apr 26 '18 at 09:14

1 Answers1

1

Try this way (ChildA has ParentA as parent):

  1. Load ParentA
  2. Set ChildA parent to NULL
  3. Save ChildA
  4. Close or flush session
  5. Open session
  6. Set ParentB to ChildA
  7. Merge ChildA (use merge not save/update/saveOrUpdate)

I think the steps 4 and 5 may not be necessary but I am not sure and you have to tray it.

Maybe 4 and 5 steps you can replace with: session.evict(ParentA)

Adam Lesiak
  • 501
  • 4
  • 10
  • Yeah, I thought about flushing but it's a little bit risky in my scenario so I prefer to avoid it... But indeed it could work :) – Dvir Apr 26 '18 at 08:20