最近在配置 Structs, Spring 和Hibernate整合的問題:
開啟OpenSessionInViewFilter來阻止延遲加載的錯誤的時候拋出了這個異常:
org.springframework.dao.InvalidDataAccessApiUsageException錯誤
但是在我們開啟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;
解決辦法1:
直接修改OpenSessionInViewFilter過濾器的配置,配置過濾器的時候配置就是在一般的配置里面加上下面藍色部分就可以了,直接指定flushMode的配置就OK了:
下面是配置文件:(web.xml)
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
解決方法2:
就是配置事務的邊界,在你方法的執行時配置事務邊界!
下面是sessionFactor.xml配置:
<!-- 事務的配置 -->
<!-- sessionFactory 為自己配置 sessionFactory 的 bean-->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<!-- execution(public * *.*.*..*.*(..)) 為自己項目中操作數據庫中的方法 -->
<aop:pointcut id="**" expression="execution(public * *.*.*..*.*(..))" />
<aop:advisor pointcut-ref="**"
advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- name 為 方法名 -->
<tx:method name="**" read-only="true" />
<tx:method name="**" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
下面是總結:
原理:因為配置openSessionInView時,啟動后他默認是給沒有配置事務邊界的方法都默認為只讀的,所以在插入數據時就會報上面的錯