报错信息: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove ‘readOnly’ marker from transaction definition.
自己并未设置过read-only,却一直报这个错,查了很多地方都是说事务里要设置propagation=“REQUIRED”,但我很奇怪,我也没开启事务啊,为什么会报这个错呢,后面试了下配置事务的办法,确实错误就解决了,我估计是SSH默认开启事务的,所以必须配置,通过XML的方式在applicationContext.xml中配置事务的代码如下(如果嫌麻烦,可以跳到文章最后面,直接利用注解的方式配置事务,很方便):
一、XML方式配置解决上述报错:
1、在DAO层继承HibernateDaoSupport (注意包别导错版本了);
2、在applicationContext.xml配置:
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务通知属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义事务传播属性 -->
<tx:attributes>
<!-- 增 -->
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<!-- 删 -->
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<!-- 改 -->
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<!-- 查 -->
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置事务切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.itheima.spring.dao.impl.CustomerDaoImpl.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
二、利用注解的方式配置:
1、在DAO层继承HibernateDaoSupport (注意包别导错版本了);
2、在Service层的类上面注解:@Transactional
(注意包别导错版本了)
3、在applicationContext.xml配置:
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
上面两种方法都可以解决Write operations are not allowed in read-only mode (FlushMode.MANUAL)的报错,赶紧试试吧,再决强调Hibernate和Spring相关jar包别导错版本了,在配置文件中用的版本和代码中用的版本要一致。