开发者

How do I update a collection on hibernate?

I have the following classes:

class A {
  Integer id;

  @OneToMany(mappedBy="parent", fetch=FetchType.EAGER, cascade={CascadeType.ALL})
  Set<B>  children;
}

class B {
  Integer id;

  @ManyToOne(fetch=FetchType.EAGER)
开发者_StackOverflow  A parent;
}

there's data in the database, say a1 that has {b1, b2, b3} as children. when i try to update a1's set of children to {b4, b5} i end up having b1..b5 in the database. in my code, i take the precaution of calling clear() on the children set, but it does not affect the database.

should i iterate and call session.delete(child) on each child of A's ?

thanks,


From Java EE 6 (and Hibernate 3.5), you should use @OneToMany(...,orphanRemoval=true)

Prior to Java EE 6/Hibernate 3.5, you can use org.hibernate.annotations.CascadeType.DELETE_ORPHAN, which was deprecated in 3.5 in favor of the addition of orphanRemoval to the JPA.


The problem is the Cascade.All on the child items. The basic problem is that even though you are clearing the set on the parent object, the child objects will save themselves as having a1 as a parent. Meaning that you need to clear BOTH sides of the relationship. There are two routes:

  1. Remove the cascade.all on the child items and let the parent object manage the entire relationship.

  2. Manually handle the relationships yourself by clearing the parent element on the child ones, or full-on deleting them from the session. In choosing this route, you are going to need to be VERY explicit about what happens to each element in the set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜