2013-03-27 50 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特定的注释,您的应用程序将不再免于供应商依赖