JPA relationship not getting updated when children are removed

前端 未结 1 829
旧时难觅i
旧时难觅i 2021-02-10 06:28

Given the following scenario:

@Entity
public class A {
  @OneToMany(mappedBy = \"a\", cascade = CascadeType.ALL)
  private List bList;
}

@Entity
public         


        
1条回答
  •  太阳男子
    2021-02-10 07:14

    JPA does not do relationship maintenence for you, the application must maintain them. That means when ever you delete an entity, the application is responsible for cleaning up any references to that entity. It is obvious when it is a foreign key relationship, as database constraints will usually cause an exception if it is not done. In the case of back references though where the relationship does not have a strict database constraint, users generally mistakenly believe that JPA will handle it - leaving the cache corrupted.

    The way to handle it is to remove any references to C and B entities. In your object model, that means fixing A's bList to remove Bs. I have seen this handled through entity remove events or in application code. Since in this case, A does not have a foreign key, you could also refresh the affected A entities from the database after the delete has occured (ie after a flush or commit).

    0 讨论(0)
提交回复
热议问题