Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid caching of entites in Spring Repository during a Transaction for tests

I have a Test like this:

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

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.

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

like image 511
Tarion Avatar asked Nov 16 '15 10:11

Tarion


People also ask

Can we use @transactional in repository?

The usage of the @Repository annotation or @Transactional . @Repository is not needed at all as the interface you declare will be backed by a proxy the Spring Data infrastructure creates and activates exception translation for anyway.

How to disable second level cache?

To disable second-level caching (say for debugging purposes), we just set the hibernate. cache. use_second_level_cache property to false.

Does spring data cache?

And since caching is not part of Spring Data JDBC and Spring Data JDBC repositories are just Spring Beans, you can combine it with any caching solution you like. The obvious choice is of course, Springs Caching abstraction behind which you can put any caching solution.

How do I clear my spring boot cache?

Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.


1 Answers

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;

Your test would then look like this:

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

    entity = textureRepository.saveAndFlush(entity );
    entityManager.clear();
    final MyEntitiy loadedTexture = myEntityRepository.findOne(entity .getId());
}
like image 73
Mathias Dpunkt Avatar answered Oct 17 '22 04:10

Mathias Dpunkt