测试时的Spring事务方法不回滚

时间:2016-05-12 08:12:29

标签: spring transactions spring-data

我想知道交易如何在春季运作,或多或少我已经学会了(或者我认为我已经学会了它)。唯一没有得到的是如下:要检查回滚是如何实现其魔力的,我创建了一个测试,该测试使用@Transacional注释调用一个方法,该注释抛出异常并查看方法更改是否保存为从外部看到的。令我惊讶的是,这一变化似乎已经发生了。

这是代码:

library(reshape2)
pmelt = melt(precisionTable, id.vars=c('VK', 'p', 'case'))
pmelt$ptShape = rep(c(19,17,15), each=6)

ggplot(pmelt, aes(x=VK, y=value)) + 
  geom_line(aes(colour=as.factor(p), shape=as.factor(ptShape))) +
  geom_point(aes(colour=as.factor(p), shape=as.factor(ptShape)), size=5)

对我来说,抛出异常是事务必须回滚,因此存储库中不需要存在保存对象。但是当我运行测试时,find方法返回保存的对象。可能有人在我错了吗?

注意:import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import org.springframework.transaction.annotation.Transactional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import repositories.files.ArchivoEnDisco; import repositories.files.ArchivosEnDiscoRepo; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = GhcserviceapiApplication.class) @WebAppConfiguration public class PruebasSinTransacciones { @Autowired ArchivosEnDiscoRepo repositorio; @Test public void compruebaTransaccionSinVariable() { // I get one far away from the last. Long id = repositorio.count() + 10l; try { inTransacction(id); fail("Exception must be throw"); } catch (Exception e) { } // I try to get the saved object ArchivoEnDisco aedOriginal = repositorio.findOne(id); assertThat("An exception ocurred so it doesn't have to find it", aedOriginal, nullValue()); } @Transactional() private void inTransacction(Long id) throws Exception { repositorio.save(new ArchivoEnDisco(id, id + "A.txt")); throw new Exception(); } } 是使用GhcserviceapiApplication注释的类。 @SpringBootApplicationArchivosEnDiscoRepo。我的pom中有CrudRepositoryspring-boot-starter-data-jpa,但未配置jpa(因此我在内存hsqldb中使用)。

修改

我因为@M而分开了课程。 Deinum评论,并尝试使用特定的hsqldb参数,但结果是一样的。

rollbackFor

1 个答案:

答案 0 :(得分:0)

Spring Transaction仅回滚Checked异常,因为Exception是部分检查类,它不会回滚事务。 您可以使用@Transactional(rollbackFor =“Throwable.class”)。

相关问题