如何避免在测试事务期间在 Spring 存储库中缓存实体
How to avoid caching of entites in Spring Repository during a Transaction for tests
我有这样的测试:
@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() 时不会调用数据库。我可以以某种方式强制它为我的测试调用数据库吗?
我希望我的测试不提交任何事务。
我无法让会话清除缓存。而且我什至不确定清除会话是否有帮助。
我知道的唯一方法是在调用查找器之前调用 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());
}
我有这样的测试:
@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() 时不会调用数据库。我可以以某种方式强制它为我的测试调用数据库吗?
我希望我的测试不提交任何事务。
我无法让会话清除缓存。而且我什至不确定清除会话是否有帮助。
我知道的唯一方法是在调用查找器之前调用 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());
}