Search code examples
hibernateinfinispansecond-level-cache

How to use 2LC and not repeat SQL query in Hibernate when row doesn't exists in database


Can Hibernate second level cache (2LC) do caching for not found records in database?

I query Account entity by primary key accountNumber - it is configured as @Cachable. If I execute em.find('AA') first time then hibernate will check 2LC, it is missed in 2LC then SQL query will be executed. There is no account AA in DB so em.find call return null.

If I execute em.find('AA') second time in another transaction then hibernate will execute SQL query again even SQL was executed before.

Is it possible that Hibernate will save null from first executed query so another SQL is not required until AA key will be invalidated in cache?

I use EAP 6.2.4, Hibernate 4.2.7, Infinispan 5.2.7


Solution

  • No. Even with Hibernate ORM 5.x, the 2LC API does not include this, and it's not possible for the 2LC implementation to return any hint that the entity cannot be in the DB either (even though the implementation could hold some kind of tombstone and know that).

    Since this might be quite useful at times, please log JIRA with feature request.