I create a new entity, store it the first time and then want to access the collections of the related classes:
@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);
}
I get the following error on the second line of logging:
org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role:
no session or session was closed
I have also tried
Hibernate.initialize(getDetailsModel().getObject().getField().getListOfSomething());
This leads to a different error:
org.hibernate.HibernateException: collection is not associated with any session
This is not very surprising when debugging I can see that the collection proxies have no session associated with them.
I am using the 'openSessionInView' filter that comes with the Spring framework. The code works fine by the way when I want to update an existing entity. It also works when I set the fetchType to eager on the collection:
@OneToMany(mappedBy = "field", fetch = FetchType.EAGER)
private List<E> listOfSomething= new ArrayList<E>();
Do I really need to set this to EAGER? I want to avoid this very much and was hoping for a way around it. Is there a way to associate a newly stored entity with the Hibernate session? I have tried both a session.load(entity)
and a session.merge(entity)
with no success.
My entities look like this:
@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;
}
What I am doing is creating a c = new C()
, selecting b
from a DropDownChoice
and on submit I want to persist getDao().save(c)
. After the submit I want to display my new entity on a different panel which is loaded via ajax. For example I want to display c.getB().getAList()
and that is where the exception happens because the b
I selected from the DropdownChoice
is a detached entity and it's aList
was not fetched and cannot be loaded lazily either.
I cannot figure out how to get the still existing session into my new C
instance.
Here's more info from my 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>