hibernate 中fetch=FetchType.LAZY问题

来源:互联网 发布:ucloud域名备案 编辑:程序博客网 时间:2024/04/28 09:33
我的实体类Deptment 中
@OneToMany(mappedBy="deptment",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    public Set<Employee> getEmployees() {
        return employees;
    }
在dao层中
public List<Deptment> queryDeptList() {
       
        List<Deptment> deptList = this.hibernateTemplate.find("from Deptment");
       
        return deptList;
    }
为什么在jsp中读取DeptmentList会报错:failed to lazily initialize a collection of role: model.Deptment.employees, no session or session was closed
这个是很典型的有懒加载引起的问题,你懒加载的时候只加载了了department的基本信息,而部门下的员工信息是懒加载的,当你要去用department下的employee信息,那么又会去加载。而此时你的session已经关闭了,所以才会报nosession错。
解决办法:在你的web.xml中添加下面的配置
<!-- 把session的关闭延迟到jsp页面显示之后,在配在struts2上面。-->
    <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>
原创粉丝点击