failed to lazily initialize a collection of role: XXXX, no session or session was closed
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<!--解決出現org.springframework.dao.InvalidDataAccessApiUsageException-->
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
http://lucky16.javaeye.com/blog/673903
在項目中使用Spring+Hibernate的時候,會開啓OpenSessionInViewFilter來阻止延遲加載的錯誤,但是在我們開啓OpenSessionInViewFilter這個過濾器的時候FlushMode就已經被默認設置爲了MANUAL,如果FlushMode是MANUAL或NEVEL,在操作過程中 hibernate會將事務設置爲readonly,所以在增加、刪除或修改操作過程中會出現如下錯誤
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition;
解決辦法:直接修改OpenSessionInViewFilter過濾器的配置,配置過濾器的時候配置就是在一般的配置裏面加上下面藍色部分就可以了,直接指定flushMode的配置就OK了:
過濾器順序的問題,應該是:
OpenSessionInViewFilter
ActionContextCleanUp
FilterDispatcher
的順序,最後調整過濾器的順序,一些問題解決
<!-- 定義事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<!-- 配置事務傳播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"></tx:method>
<tx:method name="delete*" propagation="REQUIRED"></tx:method>
<tx:method name="*" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 哪些類的哪些方法參與事務 -->
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution(* com.product.dao.*.*(..))"/>
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
</aop:config>