Hibernate Lazy Load Error after merge
I'm using vanilla Spring MVC with a custom FlashScope implementation. We basically use it to follow the Post-Redirect-Get pattern.
I've run into an odd situation. In my开发者_开发问答 Post I do some searching for the parameters the user entered, and I set those instances onto FlashScope. I see those pieces working just fine.
In the object I place onto FlashScope I have a lazy loaded collection, however when I attempt to access the collection like so:
entity.getLazyLoadedCollection();
I receive the following stacktrace:
ERROR org.hibernate.LazyInitializationException IP127.0.0.1 CV#4c44559c-c576-4732 P#75004 - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at core.model.entities.WorkflowState_$$_javassist_36.getFunctions(WorkflowState_$$_javassist_36.java)
The odd thing is that right before the call above I merge it onto the session in my service layer:
getSession().merge(entity);
Hibernate Documentation states that I should call update if I know that I'm working with a new session, but the JavaDocs make it seem like I should call merge...
As a workaround I've done the following:
if (getSession().contains(entity)) {
getHibernateTemplate().merge(person);
} else {
getSession.update(entity);
}
What should I be doing here?
Read the javadoc that you linked carefully: "Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session."
No matter what you pass to merge(), that object doesn't get associated to the session. You need to be working with the object returned from merge().
Never worked with FlashScope, but your error apeears to be because you are trying to access a LAZY
collection which has not been initialized, and you are no longer in a layer of your app which has access to the Hibernate Session
. If that assumption is correct, you need to initialize the collection where you have access to the Session
(e.g., your DAO). Here are 2 basic ways:
Hibernate.initialize(object.getMyLazyCollection());
or
if(object.getMyLazyCollection() != null) {
object.getMyLazyCollection().size(); // forces a collection load
}
精彩评论