Hibernate中onetomany hibernate设置cascade="all"的话,那么在进行联机操作的时候,如果把一端设置成inverse="false",比如one的一方,那么many一方的与one一方失去关联关系的数据不会被删除掉,而是将关联外键设置为null,出现了孤立的数据!解决办法就是设置 cascade="all-delete-orphan"。然而这种简单的设置,会出现问题。
org.springframework.orm.hibernate3.HibernateSystemException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: xxx.Aaa.bbbList; nested exception is org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: xxx.Aaa.bbbList
Caused by: org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: xxx.Aaa.bbbList
参考了论坛中的一些关于Hibernae中cascade的帖子,知道如下办法可以解决:
1 在实体中把setBbbList方法设置成私有private
2 在实体中增加如下方法:
public void addBbbList(Bbb b) {
getBbbList().add(b);
b.setAaa(this);
}
3 设置cascade="all-delete-orphan"
4 在dao中
DAO dao= (DAO) BeanFactory.getBean("dao");
Aaa a = dao.getAaaById(id);
a.getBbbList().clear();
a.addBbbList(b1);
a.addBbbList(b2);
a.addBbbList(b3);
dao.update(a);
这样与a关联的b1 b2 b3会同步到数据库,之前与a关联的子表数据将会被自动删除。
【编辑推荐】