最近在配置 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" />
<!-- 可以設置兩個pointcut,id不能相同 -->
<aop:pointcut id="**" expression="execution(public * *.*.*..*.*(..))" />
<!-- 同時將第二個pointcut 也關聯 txAdvice -->
<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時,啓動後他默認是給沒有配置事務邊界的方法都默認爲只讀的,所以在插入數據時就會報上面的錯
轉載自:http://www.cnblogs.com/clinglin/archive/2011/04/05/2005542.html