2012-04-03 81 views
2

的创建一个新的实体,存储它的第一次,然后希望访问相关的类的集合:休眠:无会话后保存新的实体

@Override 
protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {   
     final E entity = (E) form.getModelObject(); 
     getDao().save(entity); //calls session.saveOrUpdate(entity) 
     LOG.debug("Saved entity " + entity); 
     LOG.debug("Show collections " + entity.getField().getListOfSomething()); 
     parent.replaceContentPanel(parent.getDetailsPanel(parent.createReloadableModel(entity)), target); 
} 

我上第二以下错误日志的路线:

org.hibernate.LazyInitializationException: 
failed to lazily initialize a collection of role: 
no session or session was closed 

我也曾尝试

Hibernate.initialize(getDetailsModel().getObject().getField().getListOfSomething()); 

这导致了不同的错误:

org.hibernate.HibernateException: collection is not associated with any session 

这并不是很令人惊讶,当调试我可以看到集合代理没有与他们关联的会话。

我正在使用Spring框架附带的'openSessionInView'过滤器。当我想要更新现有的实体时,代码可以正常工作。当我将fetchType设置为渴望集合时,它也可以工作:

@OneToMany(mappedBy = "field", fetch = FetchType.EAGER) 
private List<E> listOfSomething= new ArrayList<E>(); 

我真的需要将它设置为EAGER吗?我非常想避免这种情况,希望能有办法解决这个问题。有没有办法将新存储的实体与Hibernate会话关联起来?我已经尝试了session.load(entity)session.merge(entity)都没有成功。

我的实体是这样的:

@Entity class A { 
    @ManyToOne B b; 
} 

@Entity class B {  
    @OneToMany(mappedBy = "b") List<A> aList; 
    @OneToMany(mappedBy = "b") List<C> cList; 
} 

@Entity class C { 
    @ManyToOne B b; 
} 

什么我做的是创造一个c = new C(),从DropDownChoice选择b并提交我要坚持getDao().save(c)。提交之后,我想在通过ajax加载的不同面板上显示我的新实体。例如,我想显示c.getB().getAList(),这是发生异常的原因,因为从DropdownChoice中选择的b是分离的实体,并且它的aList未被提取,也无法延迟加载。

我无法弄清楚如何将仍然存在的会话放入我的新C实例中。

下面是从我web.xml

<filter> 
    <filter-name>opensessioninview</filter-name> 
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>   
</filter> 
<filter-mapping> 
    <filter-name>opensessioninview</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 
+0

您正在使用的'openSessionInView'过滤器,事务何时/何地启动并提交? – rotsch 2012-04-03 07:26:19

+0

你的实体是怎样的?例如。保存操作是否会级联到集合? – bert 2012-04-03 08:32:55

+0

请包含web.xml的相关部分(调度程序servlet和OpenSessionInView过滤器) – pap 2012-04-03 14:00:55

回答

-1

我发现了一个变通,让我强制加载我知道我会需要Hibernate.initialize(...)

final ListModel<B> listModel = new ListModel<B>(bList); 
for (final B b : bList) { 
    Hibernate.initialize(b.getAList()); 
} 
add(new DropDownChoice<B>("b", listModel, new ChoiceRenderer<B>("name", "id"))); 

当我从这个片段添加2-4行到我的形式B所有实例的集合是我可能以后选择我的新实例C将有一个初始化列表A

我只对此感到高兴。我仍然希望能够根据需要将对象附加到休眠会话。

0

更多信息适当的解决方法是合并(),它包含访问该集合前集合的对象。

+0

我尝试合并原始实体,我尝试合并相关的包含集合的那个实体。既没有作用 - .- – Yashima 2012-04-03 12:39:18