ssm发生异常后无法回滚

关于ssm整合的时候spring管理事务总是自动提交

在使用spring整合mybatis时,由于不能用到sqlSession来对事物进行管理,必须要利用spring框架对Service进行事务管理。

但是发现自动管理的时候,即使出现了异常,它也还是自动提交,如下:


@Transactional
@Service("studentService")
public class StudentServiceImp implements StudentService {
	@Resource(name="studentMapper")
	private StudentMapper studentMapper;
	
	
	

	
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void deleteIds(Long[] ids) {
		
		try {
			this.studentMapper.deleteIds(ids); 			//删除学生操作
			System.out.println(1/0);							//故意除0造成异常
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}

}

applicationContext.xml:

<!-- 管理事务的代码 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">      
	 	<property name="dataSource" ref="dataSource"/>     <!-- 这玩意依赖于连接池 -->
	</bean>
	 
	 <tx:annotation-driven transaction-manager="transactionManager"/>  //采用注解的方式

明明出现了异常错误,可事务却还是自动提交了,没有发生回滚

通过网上搜寻,如果变成手动管理事务就不会发生这样的事情了。

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false, rollbackFor=Exception.class)
@Service("studentService")
public class StudentServiceImp implements StudentService {
	@Resource(name="studentMapper")
	private StudentMapper studentMapper;
	

	@Autowired
	private DataSourceTransactionManager transactionManager;  	//事务管理器
	

	
	
	@Override
	public void deleteIds(Long[] ids) {
		//以下是手动开启事务 发现怎么样都会自动提交,所以干脆用手动提交代码
		//1.获取事务定义
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		//2.设置事务隔离级别,开启新事务
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		//3.获得事务状态
		TransactionStatus status = transactionManager.getTransaction(def);
		
		try {
			this.studentMapper.deleteIds(ids);
			System.out.println(1/0);
			transactionManager.commit(status);
		} catch (Exception e) {
			System.out.println("出现异常");
			transactionManager.rollback(status);
		}
	
	}

}

通过手动管理事务,不会发生无法回滚的情况了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值