【问题标题】:How to avoid caching of entites in Spring Repository during a Transaction for tests如何在测试事务期间避免在 Spring Repository 中缓存实体
【发布时间】:2016-02-17 10:17:38
【问题描述】:

我有一个这样的测试:

@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());
}

这工作得很好。但是当我删除事务的提交代码时,存储库在调用 findOne() 时不会调用数据库。我可以以某种方式强制它为我的测试调用数据库吗?

我希望我的测试不提交任何事务。

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

【问题讨论】:

  • 一个 worarround 是使用 findAll(),因为我只想执行对我有用的 UserType :)
  • .findOne 应该更改为.getOne,它们是不同的。除此之外,为什么您需要强制它进行数据库调用。没必要。

标签: spring spring-data-jpa


【解决方案1】:

我知道的唯一方法是在调用查找器之前调用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());
}

【讨论】:

  • 我写了一个全新的问题,在最后一秒我看到了这个......谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2012-08-19
  • 1970-01-01
相关资源
最近更新 更多