在springboot中关于@Transactional事务注解不能回滚的原因

	@Override
	@Transactional(readOnly = false,rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public ResultBean test(GoodsInfo goodsInfo) {
		try {
			GoodsInfo goodsInfo1 = new GoodsInfo();
			goodsInfo1.setId("4");
			goodsInfo1.setGoodsName("测试4");
			goodsInfo1.setGoodsTitle("测试4的标题");
			GoodsInfo goodsInfo2 = new GoodsInfo();
			goodsInfo2.setId("5");
			goodsInfo2.setGoodsName("测试5");
			goodsInfo2.setGoodsTitle("测试5的标题");
			GoodsInfo goodsInfo3 = new GoodsInfo();
			goodsInfo3.setId("2");
			goodsInfo3.setGoodsName("测试6");
			goodsInfo3.setGoodsTitle("测试6的标题");
			goodsInfoMapper.testRollback(goodsInfo1);
			System.out.println("执行完了第一次");
			goodsInfoMapper.testRollback(goodsInfo2);
			System.out.println("执行完了第二次");
			goodsInfoMapper.testRollback(goodsInfo3);
			System.out.println("执行完了第三次");
			ResultBean resultBean = new ResultBean(CommonErrorEnum.SUCCESS);
			resultBean.setResult("OK");
			return resultBean;

		}catch (Exception e){
			e.printStackTrace();
		}
		return new ResultBean<>(CommonErrorEnum.MYSQL_ERROR);
	}

 

 

这是我第一次写的情况,此时不发生回写,是因为他们中间发生了异常,由于我写了try catch,所以,所有发生的异常都是由我自己去操作的,外面是看不到异常的,,,,而事务的回滚是发生由你自己定义的异常才会发生回滚,由于异常没有跑出去,所以没有回滚

 

修改之后(把try catch去掉即可):

        @Override
	@Transactional(readOnly =        false,rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public ResultBean test(GoodsInfo goodsInfo) {
	        GoodsInfo goodsInfo1 = new GoodsInfo();
		goodsInfo1.setId("4");
		goodsInfo1.setGoodsName("测试4");
		goodsInfo1.setGoodsTitle("测试4的标题");
		GoodsInfo goodsInfo2 = new GoodsInfo();
		goodsInfo2.setId("5");
		goodsInfo2.setGoodsName("测试5");
		goodsInfo2.setGoodsTitle("测试5的标题");
		GoodsInfo goodsInfo3 = new GoodsInfo();
		goodsInfo3.setId("2");
		goodsInfo3.setGoodsName("测试6");
		goodsInfo3.setGoodsTitle("测试6的标题");
		goodsInfoMapper.testRollback(goodsInfo1);
		System.out.println("执行完了第一次");
		goodsInfoMapper.testRollback(goodsInfo2);
		System.out.println("执行完了第二次");
		goodsInfoMapper.testRollback(goodsInfo3);
		System.out.println("执行完了第三次");
		ResultBean resultBean = new ResultBean(CommonErrorEnum.SUCCESS);
		resultBean.setResult("OK");
		return resultBean;

此时,就可回滚,,,,,

 

 

你可能感兴趣的:(添加事务不回滚,@Transactional)