Search code examples
jpaobjectdb

objectdb : update child set<> of the parent after remove one child doesn't work


In my application I have two entity Person and Activity

@Entity
public class Person
{
  .
  .
  .
  @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER,orphanRemoval=true)
  Set<Activity> a;

  // getters setters constructors
}

... and...

@Entity
public class Activity
{
  .
  .
  .
  // getters setters constructors
}
  1. In the first place I create two Activity's objects
  2. I add activity's objects to a Person object
  3. I persist the Person object (the two activity objects are persisted, it work fine)
  4. Then I delete one Activity object from my database
  5. I select my Person object from the database

The result is a Person object with Set<Activity> with size=2.

Can someone help me please?


Solution

  • When you remove the Activity object from the database you have to update the set in Person and remove that Activity object also from the set. Otherwise you will have a broken reference to a non existing Activity object in the set.

    On the other hand, since you enabled orphanRemoval, you can just remove the Activity from the set in Person and it should be removed automatically also from the database.

    Another option is to define the set as mappedBy and then the set will be updated automatically when an Activity is removed from the database, when the Person object is loaded again from the database or refreshed.