@Entity
public class Parent {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
int id;
@OneToMany(cascade=CascadeType.REMOVE)
List<Item> children = new ArrayList<Child>();
}
@Entity
public class Child {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
int id;
}
As you can see above, I have a OneToMany-Relation between parent and child. If I delete an instance of parent, all children are also deleted. Is there a way to get this working the other way round as well?
Parent p = new Parent();
Child c = new Child();
p.children.add(c);
EntityManager.persist(p);
EntityManager.persist(c);
EntityManager.remove (c);
This code runs without exception, but when I load p the next time, there is a new child attached.
If you want deletes to work from both sides, you need to define a bi-directional relationship between
ParentandChild: