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

Tar*_*ion 11 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());
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Mat*_*nkt 18

我知道的唯一方法是entityManager.clear()在调用finder之前调用.我想你可以自动EntityManager进入你的测试:

@Autowired
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)

您的测试将如下所示:

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

    entity = textureRepository.saveAndFlush(entity );
    entityManager.clear();
    final MyEntitiy loadedTexture = myEntityRepository.findOne(entity .getId());
}
Run Code Online (Sandbox Code Playgroud)