hibernate中使用load方法,could not initialize proxy - no Session

来源:互联网 发布:windows安装centos系统 编辑:程序博客网 时间:2024/06/06 14:06
在使用load出来的代理对象的时候,如果在session关闭后使用,则会报错
有几种方式
1.使用get方法取出对象,但是如果这个对象的某个属性是lazy加载的,比如User有一个Group关联对象的fetchType是Lazy,那么在session关闭后取user.getGroup(),还是无法获取。
2.spring提供了一个Filter,让session在jsp加载完成后关闭。
spring中对OpenSessionInViewFilter的描述如下:
它是一个Servlet2.3过滤器,用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定。目的是为了实现"Open Session in View"的模式。
配置在web.xml中
     <!--OpenSessionInViewFilter 解决延迟加载问题--> 
    <filter> 
            <filter-name>OpenSessionInViewFilter</filter-name> 
            <filter-class> 
                     org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
            </filter-class> 
            <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView --> 
            <init-param> 
                    <param-name>singleSession</param-name> 
                    <param-value>true</param-value> 
            </init-param> 
    </filter> 
    <filter-mapping> 
            <filter-name>OpenSessionInViewFilter</filter-name> 
            <url-pattern>/*</url-pattern> 
    </filter-mapping>

这个filter得放到struts2的filter的前面。 

如果配置了OpenSessionInViewFilter,但是在spring中没有配置transaction,那么会有一个Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition
这样的异常。
这是因为默认的事务边界在dao层。如果spring没有配置事务边界,那么spring的OpenSessionInViewFilter拦截到任何的调用都会认为session的调用是只读的。
原创粉丝点击