3

i have a simple one to many mapping in my project...let's suppose that i have 1 father object and 3 child objects stored in my DB. the problem occurs when i load the father object and change the number of sons (for example removing one of them). When i try to update the father object, the son that is no longer in the child's set it's still on the DB. Is there a way to delete the unwanted child without have to manually proceed?

Medioman92
  • 581
  • 4
  • 10
  • 21
  • Is the "Cascade" option set to "all" on the collection? – Davos555 Aug 05 '13 at 13:02
  • You need "delete orphans". Cascade means that when creating the the parent, the child is created too, when removing the parent, the child is removed too and so on. Nobody ever said that when you remove the child from the list, that it is removed from the DB. – Stefan Steinegger Aug 05 '13 at 13:22
  • yep...and it's also set the "mappedBy" parameter – Medioman92 Aug 05 '13 at 13:24
  • I think this link might help you, http://stackoverflow.com/questions/14686595/hibernate-onetomany-remove-child-from-list-when-updating-parent Have a look, change to your need according.. – Jayesh Aug 05 '13 at 13:02
  • @Jayesh so to just remove one item from the list using `.clear()` command i have to copy the list, clear it and then manually re-add all'items ?? not very practicle – Medioman92 Aug 05 '13 at 13:30
  • @Medioman92 Why `clear()` the list? Just remove the entity you want to remove from the list and delete it from the database? No need to clear the whole list and re-populate it again. – Magnilex Aug 06 '13 at 11:03
  • @Magnilex i'm working only with the father object (the update method is called on this object)...if possibile i'd like to avoid the need of working with children object – Medioman92 Aug 06 '13 at 11:36

1 Answers1

2

You can use the attribute orphanRemoval=true on the @OneToMany annotation.

Crferreira
  • 1,218
  • 2
  • 10
  • 22