springboot 测试,事务相关

springboot测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestServiceImplTest {

    @Autowired
    TestService testService;

    @Test
    public void add() throws Exception {
        TestBean testBean = new TestBean();
        testBean.setId(337595516089008160L);
        System.out.println(testService.add(testBean));
    }

}

这种情况下,是默认没有开启事务回滚的,当测试完成不会回滚数据.

开启测试完成回滚

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback
public class TestServiceImplTest {

    @Autowired
    TestService testService;

    @Test
//    @Rollback
    public void add() throws Exception {
        TestBean testBean = new TestBean();
        testBean.setId(337595516089008160L);
        System.out.println(testService.add(testBean));
    }

}

测试完成后,会类似看到下面输出,同时数据也会回滚.

2017-07-20 16:41:25.286  INFO 12528 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@a3d8174 testClass = TestServiceImplTest,

Rollback注解,默认值true,开启回滚,可以在类上,也可以方法上

@Transactional(readOnly = true) 含义.

一直以来的理解都是声明只读事务,对其进行优化,当执行插入操作的时候抛出异常.

今天将其加在一个insert方法上面,发现测试插入成功.

  @Transactional(rollbackFor = Exception.class,readOnly = true)
    public int add(TestBean testBean) {
        int i =  testMapper.insert(testBean);
        return i;
    }

阅读源码.

	/**
	 * {@code true} if the transaction is read-only.
	 * <p>Defaults to {@code false}.
	 * <p>This just serves as a hint for the actual transaction subsystem;
	 * it will <i>not necessarily</i> cause failure of write access attempts.
	 * A transaction manager which cannot interpret the read-only hint will
	 * <i>not</i> throw an exception when asked for a read-only transaction
	 * but rather silently ignore the hint.
	 * @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()
	 */
	boolean readOnly() default false;

发现readOnly = true 只是对底层系统暗示要求只读事务,当底层支持时才会针对插入操作抛出异常,当不支持时,默默忽略(而大部分简单的jdbc都是不支持的)

Transactional 注解在父类上,子类有效

转载于:https://my.oschina.net/superwen/blog/1476522

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值