SHH could not initialize proxy - the owning Session was closed 和延迟加载问题

1.SSH使用时,出现could not initialize proxy - the owning Session was closed 时的解决方案。
could not initialize proxy - the owning Session was closed
解决、
第一步、去掉hibernate的延迟加载
<filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>
     org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    </filter-class>
</filter
<filter-mapping>
    <filter-name>hibernateFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping>
第二步、 hbm.xml中 lazy="false"
<many-to-one name="deptInfo" lazy="false">
            <column name="deptId"/>
        </many-to-one>
2.<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
        org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    </filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<!-- 和 spring 中的sesssionfactory ID 一致 --><init-param><param-name>sessionFactoryBeanName</param-name><param-value>sessionFactory</param-value></init-param></filter><filter-mapping><filter-name>hibernateFilter</filter-name><url-pattern>*.do</url-pattern><!-- *.jsp, *.do--></filter-mapping>
不过, 这时候又会导致更新数据时抛出如下异常:
Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

这时候再去网上找解决方案, 会有人说: 把参数 singleSession改为false, 就行了. 不过, 改完后, 估计不久就会遇到另一个郁闷的异常:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

这下完了, 两个方案都不行, 到底怎么办? 还好, 在http://xuliangyong.iteye.com/blog/144818的主页上, 给了一个方案, 就是改写 OpenSessionInViewFilter 的代码, 非常感谢, 下面给出的就是最终方案:

web.xml

< filter-name >hibernateFilter</filter-name>

< filter-class > org.springframework.orm.hibernate3.support.OurOpenSessionInViewFilter </filter-class>

OurOpenSessionInViewFilter.java 代码:

package org.springframework.orm.hibernate3.support;

import org.hibernate.*;

/** * 单session模式下, 默认会发生无法提交的错误: * Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition. * 需要设置FlushMode并刷新session. * 参考: http://xuliangyong.iteye.com/blog/144818 * @author 刘长炯 */publicclass OurOpenSessionInViewFilter extends OpenSessionInViewFilter {
   
    public OurOpenSessionInViewFilter() {
        super.setFlushMode(FlushMode.AUTO);
    }

    protectedvoid closeSession(Session session, SessionFactory sessionFactory) {
        session.flush();
       
        try {
            session.getTransaction().commit();
        } catch (HibernateException e) {
            // TODO Auto-generated catch block//e.printStackTrace();
        }
       
        super.closeSession(session, sessionFactory);
    }
}

解决使用1的方法

你可能感兴趣的:(spring,jsp,Hibernate,orm,ssh)