JPA 移除 HashSet 內的物件
直接透過 Entity 作 remove 再 save 進 DB 是沒有用的,要用 EntityManager 來 remove
//沒用,存進 DB 也不會刪除
public void removeStudent(Student stu){
this.students.remove(stu);
}
要這樣才行
entityManager.remove( child );
其實 Hibernate 同樣也是要用 session 刪除
However, the following code:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
c.setParent(null);
session.flush();
will not remove c from the database. In this case, it will only remove the link to p and cause a NOT NULLconstraint violation. You need to explicitly delete() the Child.
Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
session.delete(c);
session.flush();