Connection is read-only. Queries leading to data modification are not allowed

本文介绍如何在Spring框架中正确配置事务管理,特别是针对只读事务和数据修改事务的不同配置方式。通过具体的XML配置示例说明如何避免因配置不当导致的只读连接错误。

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

Connection is read-only. Queries leading to data modification are not allowed

Connection is read-only. Queries leading to data modification are not allowed

[html] view plain copy
  1. <span style="font-size:14px;"><tx:advice id="txAdvice" transaction-manager="txManager">  
  2. <tx:attributes></span>  

<!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 -->
<!-- method name=*, readonly=true表示所有的数据库操作都可以使用,但是只能是读取数据库。
例如有UserService的方法 listUsers, 获取所有用户,就没问题。
但是如果是UserService的方法delUser, 要在dao层删除用户。就会报错误如下:
Connection is read-only. Queries leading to data modification are not allowed。
因此要添加下面的每一个add*,del*,update*等等。 分别给予访问数据库的权限。
-->
[html] view plain copy
  1. <span style="font-size:14px;"><tx:method name="*" propagation="REQUIRED" read-only="true" /></span>  

<!-- 以下方法都是可能设计修改的方法,就无法设置为只读 -->
[html] view plain copy
  1. <span style="font-size:14px;"><tx:method name="add*" propagation="REQUIRED" />  
  2. <tx:method name="del*" propagation="REQUIRED" />  
  3. <tx:method name="update*" propagation="REQUIRED" />  
  4. <tx:method name="save*" propagation="REQUIRED" />  
  5. <tx:method name="create*" propagation="REQUIRED" />  
  6. <tx:method name="clear*" propagation="REQUIRED" />  
  7. </tx:attributes>  
  8. </tx:advice></span>  

在上面的beans.xml配置中, 一开始没有配置add*,del*,update*等等。 就会在调用相应的方法时出错。

而获取数据则没有问题, 是因为有

[html] view plain copy
  1. <span style="font-size:14px;"><tx:method name="*" propagation="REQUIRED" read-only="true" />  
  2. <pre name="code" class="html"><context:component-scan base-package="com.eq3z" />  
  3. <!-- 配置事务管理器 -->  
  4. <bean id="transactionManager"  
  5. class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  6. <property name="sessionFactory" ref="sessionFactory" />  
  7. </bean>  
  8. <!-- 配置事务传播特性 -->  
  9. <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  10. <tx:attributes>  
  11. <tx:method name="save*" propagation="REQUIRED"/>  
  12. <tx:method name="update*" propagation="REQUIRED"/>  
  13. <tx:method name="delete*" propagation="REQUIRED"/>  
  14. <tx:method name="*" read-only="true"/>  
  15. </tx:attributes>  
  16. </tx:advice>  
  17. <!-- 定义使用事务管理的方法 -->  
  18. <aop:config>  
  19. <aop:pointcut id="managerMethod" expression="execution(* com.service.*.*(..))"/>  
  20. <aop:advisor pointcut-ref="managerMethod" advice-ref="txAdvice"/>  
  21. </aop:config></span> 














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值