如何在测试事务期间避免在Spring存储库中缓存实体 [英] How to avoid caching of entites in Spring Repository during a Transaction for tests

查看:89
本文介绍了如何在测试事务期间避免在Spring存储库中缓存实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的测试:

@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()时将不会调用数据库.我能以某种方式强迫它使数据库调用我的测试吗?

This works perfectly fine. But when I remove the Committing code for the transaction, the repository will not call the database when calling findOne(). Can I somehow force it to make the database call for my Tests?

我希望我的测试不提交任何交易.

I prefer my test to not commit any transaction.

我无法通过Session清除缓存.而且我什至不确定清除会话是否有帮助.

I'm not able to get the Session to clear the cache. And I'm not even sure if clearing the session would help.

推荐答案

我知道的唯一方法是在调用查找程序之前先调用entityManager.clear().我认为您可以将EntityManager自动连接到测试中:

The only way I know is to call entityManager.clear() before calling the finder. I think you can autowire the EntityManager into your test:

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

这篇关于如何在测试事务期间避免在Spring存储库中缓存实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆