日期:2014-05-18  浏览次数:20696 次

collection is not associated with any session
S2SH整合时
在spring中已经配置了相应的事务

<tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
         <!-- 指定哪些方法需要加入事务,这里懒惰一下全部加入,可以使用通配符来只加入需要的方法 -->  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>  
            <tx:method name="browse*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="load*" propagation="REQUIRED" read-only="true"/> 
            <tx:method name="*" propagation="REQUIRED" />  
        </tx:attributes>  
    </tx:advice>   
    <!-- 需要引入aop的命名空间 -->  
    <aop:config>  
       <!-- 切入点指明了在执行Service的所有方法时产生事务拦截操作 -->  
        <aop:pointcut id="daoMethods" expression="execution(* com.mcshop.service.*.*(..))" />      
        <!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" />  
   </aop:config>           


public void initAddress(UserBean user) {
Hibernate.initialize(user.getAddress());
}

我觉得这样应该在每次执行service内的方法时都会把session打开吧?为什么还报没有相应的session的错误
------解决方案--------------------
采用延迟加载了吗,或者其它地方已经把session关闭了
------解决方案--------------------
这应该是延迟加载造成的,设置fetch属性了吗
------解决方案--------------------
引用:
还有我在spring中杂这些方法上加入事物了,那进入这个方法时session就应该打开一个session了,为什么还会出现这个错误?
因为事务提交后,session就会自动关闭。如果是属性的延迟加载,在你的实体配置文件中的指定字段加lazy="true"。
------解决方案--------------------
如果你仍想使用延迟加载的话,那就扩大session的生命周期,配置OpenSessionInView,它是与事务结合使用的