Skip to content
Advertisement

First level cache not working with JPA and Hibernate

I an new to use hibernate caching (first level, 2nd level and query cache).

My project is configured using Spring MVC and JPA.

I am testing first level cache using JUnit test case below.

JavaScript

And my entity class is defined as :

JavaScript

This should execute native query once in case first level cache is by default enabled. But I am getting result below while executing this query:

JavaScript

Below is my persistence related configurations:

JavaScript

Can anybody help me to sort out an issue or anything I am doing wrong ?

Thanks in advance !

Advertisement

Answer

You need to annotate the test method with @Transactional or use the Spring TransactionTemplate.

Even if retrieving an entity doesn’t require a transaction, grouping multiple calls inside one would clearly specify the Persistence Context boundaries (where it is meant to start and where it should end).

To replicate the 1st Level Cache you need the same Unit Of Work throughout your test method, and annotating the test with @Transactional would start a transaction (a Spring logical transaction that’s bound to the current executing Persistence Context transaction which correlates to the actual physical database transaction).

When the test method ends the Transaction is usually roll-back so no changes will be propagated to any successive test, but within the currently executing test method you get to see your own changes, which is the Isolation property in ACID.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement