LazyInitializationException in spite of OpenSessionInViewFilter

只愿长相守 提交于 2019-12-03 09:42:27

Two most common causes I know of for lazy load exceptions with the filter on are either trying to access something after an exception has invalidated the Hibernate Session, or trying to access a field on something that was actually sitting around on the Web session and isn't attached.

public interface EntityService {

  @Transactional
  EntityA getA(Long id);

  @Transactional
  EntityB getB(Long id);
}

public class WebPageController {

  public void handleGet(Long id1, Long id2) {
    EntityA a = entityService.getA(id1);
    try {
      EntityB b = entityService.getB(id2);
    } catch (Exception e) {
      //print somthething
    }
    a.accessLazyField(); //will throw lazy load after getB throws exception
  }
}

Obviously lots of code and annotations ommitted for clarity :)

@SessionAttributes("model")
public class WebPageController {

  @ModelAttribute("model")
  @RequestMapping(method=RequestMethod.GET)
  public EntityA handleGet(Long id) {
    return entityService.getA(id);
  }

  @RequestMapping(method=RequestMethod.POST)
  public String handlePost(@ModelAttribute("model") EntityA a) {
    a.accessLazyField(); //will throw lazy load if the field was not accessed during original page rendering
    return "viewName";
  }
}

In spring MVC You should use OpenSessionInViewInterceptor instead of filter In my current project this is configured that way:

<mvc:annotation-driven/>
<mvc:interceptors>
<bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
</mvc:interceptors>

Where sessionFactory refers to org.springframework.orm.hibernate3.LocalSessionFactoryBean

Works flawless.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!