hibernate报错异常总结
1、a collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance
hibernate中one to many设置cascade="all"的话,那么在进行联机操作的时候,如果把一端设置成inverse="false",当进行删除的时候,删除one表记录, many一方 不会删除,而是把关联字段设置成null,这样会出现孤立的 many方 数据!解决办法就是设置 cascade="all-delete-orphan"。然而这种简单的设置,会出现上述问题。
当<set name="children" inverse="true" cascade="all">时,通过parent.getchildren().remove(child1);只是使child1游离成为一个“孤儿”,并不能将child1持久化到数据库表中的记录也删除。但如果cascade="all-delete-orphan"(orphan为“孤儿”),则会将child1持久化到数据库表中的记录也删除掉。
// 酒店:hotel 标志物:building
// 这二者之间是一对多的关系,一个酒店对应多个标志物。
// 酒店的配置文件中设置了对标志物的 cascade="all-delete-orphan"
执行如下代码:
tbhoteldao hoteldao =new tbhoteldao();
tbhotel hotel = hoteldao.findbyid(44);
hotel.sethotelname("12345");
tbbuilding building2 = new tbbuilding();
building2.settbhotel(hotel);
building2.setdistance("234米");
building2.setbuildingname("阿斯顿");
set tbbuildings = new hashset();
tbbuildings.add(building2);
hotel.settbbuildings(tbbuildings);
hoteldao.update(hotel);
报出如下异常:
a collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance:。。。。。。。。。。。
解决办法:
将代码
set tbbuildings = new hashset();
tbbuildings.add(building2);
hotel.settbbuildings(tbbuildings);
修改为:
set tbbuildings = hotel.gettbbuildings();
tbbuildings.clear();
tbbuildings.add(building2);