Query Cache concurrency issue

We’re using Hibernate 5.4.32.Final and experiencing an issue with cacheable queries and concurrent sessions:

Consider the following code:

Session session = openHibernateSession(); 

Person a = new Person();



// time t1

Criteria critera = session.createCriteria(Person.class);
Person personFromQuery = (Person) criteria.uniqueResult();



This works fine and the personFromQuery returns as expected (not null)

The problem we’re experiencing is in the case another session (from another thread) executes the same query (which is cacheable) at time t1, i.e after the flush of the first session. in this case - personFromQuery returns null

the reason this is happening is because session2 runs the query before session1 was committed and therefore it puts empty result in the queryCache. when session1 runs the query - it get’s the result that session2 placed in the queryCache, which are not correct from session1 point of view.

Is this behavior expected or is this a bug? can it be resolved with configuration?

I think you can configure the cache to be transactional, but that depends on the cache you are using. See Hibernate ORM 5.6.10.Final User Guide

I think you can configure this by annotating @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)