A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.daqsoft.qs.entity.Answer.fillItems;異常


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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM