在Spring Framework 3的单元测试中,针对数据库单元测试,我们一般会采用“@Rollback(true)”进行回滚,如下:
@RunWith(SpringJUnit4ClassRunner.class)// 引入Spring配置文件@ContextConfiguration(locations = { "classpath:/META-INF/springContext/service-context.xml" })public class EmailActionServiceTest { @Test @Rollback(true) public void testSave() { assertThat(actionService, IsNull.notNullValue()); // 示例代码 EmailAction action = new EmailAction(); action.setUserId(100L); action.setEnterTime(new Date()); action.setUsername(10); actionService.save(action); assertThat(action.getId(), IsNull.notNullValue()); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
但在Spring Boot中,我们发现“@Rollback(true)”已经无法回滚数据,对数据库操作完全无效,经过查阅Spring Boot的单元测试文档,发现数据回滚的注解已改为“@Transactional”,正确的用法如下:
@RunWith(SpringRunner.class)@SpringBootTest@Import(ServiceConfiguration.class)public class EmailActionServiceTest { @Resource private EmailActionService actionService; @Test @Transactional public void testSave() { assertThat(actionService, IsNull.notNullValue()); EmailAction action = new EmailAction(); action.setUserId(100L); action.setEnterTime(new Date()); action.setUsername(10); actionService.save(action); assertThat(action.getId(), IsNull.notNullValue()); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
在这里,“@Transactional”注解有两个出处,一是来自JAVA官方,包名为“javax.transaction”,一是来自Spring Framework,包名为“org.springframework.transaction.annotation”,在Spring框架中,大部分的情况下,它们都可以交换使用,效果是等价的,只不过Spring Framework提供的“@Transactional”功能更强,粒度更细,例如支持“TransactionManager”的配置、支持隔离性(isolation)、只读(isolation)、超时(timeout)等特性,所以如果希望更高控制力度的事务管理,那么Spring Framework的“@Transactional”将是你的最佳选择,如果更多考虑扩展性、兼容性的话,那么JAVA官方“@Transactional”当仁不让。