2013-03-27 51 views
0

我對一堆實體有一對多的關係。但是,我並不總是希望爲孩子定義一個值。既然它可以是一對多的,它可能是空的。一對多冬眠設置值jpa

當我沒有創建子對象時,我的測試失敗並且違反了參照完整性約束。

我試着給連接添加可爲空的true,但似乎沒有解決問題。

@JoinColumn(name = "image_relation") 
@LazyCollection(LazyCollectionOption.FALSE) 
@OneToMany 
private List<Image> productImageGroup; 

我試着使用fetch類型的渴望並得到了不同的錯誤。

@JoinColumn(name = "product_item_relation") 
@OneToMany(fetch=FetchType.EAGER) 
private List<ProductItems> productItemGroup; 

拋出:

Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags 
+2

這很可能與LazyCollection有關,通常沒有任何問題具有null onetomany關係。 – 2013-03-27 12:56:56

+0

在我開始做LazyCollection之前,我已經獲取了渴望的類型,然後當我添加第二個onomanomany時,我遇到了太多的行李問題。 – zmanc 2013-03-27 13:57:52

+0

你看過http://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags? – sharakan 2013-03-27 14:06:42

回答

1

問題最有可能與@LazyCollection被missused。

當多個List被提取時,拋出多個Bag異常。你可以用兩種方法解決這個問題:

用一個集合替換列表。任何數量的集合都可以被熱切地獲取。

@JoinColumn(name = "product_item_relation") 
@OneToMany(fetch=FetchType.EAGER) 
private Set<ProductItems> productItemGroup; 

或者刪除預先抓取和處理這個程序中的代碼

@JoinColumn(name = "product_item_relation") 
@OneToMany 
private List<ProductItems> productItemGroup; 

public List<MyObject> getMyObjects(){ 
    List<MyObject> objects = entityManager.createQuery("SELECT o FROM MyObject o").getResultList(); 
    // OneToMany not fetched yet 
    for(MyObject o : objects) 
     Hibernate.initialize(o.getProductItemGroup()); // Same as simply accessing the list to force loading, but states your intention more clearly. 
    // OneToMany collection is now fetched. 
    return objects; 
} 

您可以改善這種性能大大指定的收集@org.hibernate.annotations.Fetch(fetchMode)並指定子查詢或加入。請注意,這是一個hibernate特定的註釋,您的應用程序將不再免於供應商依賴