2

So my POI is when you have an @Entity with a collection. Let's say you fetch the entity with a collection of items. Now let's assume the collection has entries. My question is: what happens if you replace the collection that has:

Item(id: 1, name: "box"), Item(id:2, name: "plate")

with a collection that has:

Item(id:2, name: "puppy")

So: Item with id == 1 goes away if delete orphans is true and cascade is enabled. But when item with id == 2 is replaced, does it get updated to have label "puppy" instead of "plate" ?

What are the gotchas in spring boot when using @Transactional ?

C-Otto
  • 5,615
  • 3
  • 29
  • 62
Xeperis
  • 1,449
  • 2
  • 25
  • 41

1 Answers1

3

If you have fetched a collection in the session, you are not supposed to "replace" it with a new one. Instead, you should update the existing one.

If you want to remove an entry from this collection, then get the iterator and call "remove" on it for that entry. If you want to update an entry, just get it out and update it. The previous entry which you didn't touch will stay in DB as it is.

"delete-orphans" comes into picture if you have iterated over the collection and have removed some of its entries. So the association between parent and child doesn't exist anymore and you don't want child to survive independently.

This might help too - Hibernate deleting orphans when updating collection

Community
  • 1
  • 1
Sanjeev Dhiman
  • 1,169
  • 1
  • 11
  • 20
  • do you have a reference where it says that "If you have fetched a collection in the session, you are not supposed to "replace" it with a new one. Instead, you should update the existing one." ? – Zartc Oct 03 '18 at 08:30
  • Actually, problem may occur w.r.t. orphan removals if the collection was replaced. I could write up some code but here's the ready reference - https://stackoverflow.com/questions/15911558/is-it-legal-to-replace-a-list-by-an-other-one-in-an-hibernate-jpa-entity – Sanjeev Dhiman Oct 04 '18 at 07:29