如何在测试事务期间避免在Spring Repository中缓存entites

时间:2015-11-16 10:39:02

标签: spring spring-data-jpa

我有这样的测试:

@Transactional
@Test
public void addRemoveTest() {
    MyEntitiy entity = new MyEntitiy ();

    entity = textureRepository.saveAndFlush(entity );
    TestTransaction.flagForCommit();
    TestTransaction.end();
    TestTransaction.start();
    final MyEntitiy loadedTexture = myEntityRepository.findOne(entity .getId());
}

这完全没问题。但是当我删除事务的Committing代码时,存储库在调用findOne()时不会调用数据库。我可以以某种方式强制它为数据库调用我的测试吗?

我更喜欢我的测试不提交任何交易。

我无法让Session清除缓存。我甚至不确定清理会话是否会有所帮助。

1 个答案:

答案 0 :(得分:16)

我知道的唯一方法是在调用finder之前调用entityManager.clear()。我认为您可以将EntityManager自动装入您的测试中:

@Autowired
private EntityManager entityManager;

您的测试将如下所示:

@Transactional
@Test
public void addRemoveTest() {
    MyEntitiy entity = new MyEntitiy ();

    entity = textureRepository.saveAndFlush(entity );
    entityManager.clear();
    final MyEntitiy loadedTexture = myEntityRepository.findOne(entity .getId());
}
相关问题