Write operations are not allowed in read-only mode (FlushMode.MANUAL)

本文详细解析了在Spring框架下使用Hibernate进行数据库写操作时出现的“Write operations are not allowed in read-only mode”异常,并提供了详细的解决方案,包括配置hibernateTemplate、sessionFactory和事务管理器,以及如何正确使用@Transactional注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错信息:

严重: Exception occurred during processing request: 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.
org.springframework.dao.InvalidDataAccessApiUsageException: 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.
	at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
	at org.springframework.orm.hibernate4.HibernateTemplate$24.doInHibernate(HibernateTemplate.java:789)

原因:SSH 曾删改时,没有添加开启事务,报上面错误。

添加事务:

	在applicationContext中增加hibernate的配置信息
	
	1:hibernateTemplate
	
	    <!-- 配置hibernateTemplate -->
	    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
	        <property name="sessionFactory" ref="sessionFactory"></property>
	    </bean>
	
	2:sessionFactory
	
	    <!-- 配置sessionFactory -->
	    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	        <property name="dataSource" ref="c3p0"/>
	        <property name="configLocations" value="classpath:hibernate.cfg.xml"/><!-- 加载hibernate数据描述文件 -->
	    </bean>
	
	3:txManger
	
	    <!-- 开启事务管理 -->
	    <bean id="txManger" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
	        <property name="sessionFactory" ref="sessionFactory"/>
	    </bean>
	
	4:注解的动态代理
	
	    <!-- 开启hibernate事务注解代理,proxy-target-class默认值为false,则代表不启用事务注解,此时的代理模式为jdk代理
	    如果proxy-target-class属性值为true,则代表开启事务注解,此时代理模式为cglib代理
	    proxy-target-class设置为true之后,对于数据库事务(写)默认为只读状态,
	    可以在action中注解@Transactional中的属性值readOnly修改为false,则代表可读可写状态
	    -->
	    <tx:annotation-driven transaction-manager="txManger" proxy-target-class="true"/>

在dao或service上添加

	@Transactional(readOnly=false)//默认为true--只读状态,false----可读可写状态

上面报错问题解决!

如果把@Transactiona添加到controller上则 @Autowired和@Resource 失效! 空指针异常。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值