Reputation: 2485
I have an application that uses 2nd level cache on a JBoss AS 7 installation (Infinispan 2nd level cache provider).
We have some update JPQL Queries that invalidate the cache- I wonder what will be the effect if we include some native SQL queries in our application. Will the Query cache be invalidated ?
Also I remember using the sqlQuery.addSynchronizedQuerySpace("") instruction on Hibernate to prevent cache invalidation for some native SQL queries. Is it possible to do it also with JPA ?
Thanks!
Upvotes: 2
Views: 3312
Reputation: 597
From Hibernate Query Spaces - Optimizing Flush and Cache Operations:
Since Hibernate 5.3.20 and 5.4.24, you can also provide the query space as a query hint. The main benefit of this approach is that you can use it with JPA’s Query interface. You no longer need to cast it to one of Hibernate’s proprietary interfaces.
Upvotes: 0
Reputation: 97120
I came across this question when dealing with the same problem today, so I thought I'd post my findings here.
Using JPA native UPDATE/INSERT/DELETE queries does cause Hibernate to invalidate the entire 2nd level entity cache. As you mentioned in your question, Hibernate has a workaround for this, but it seems to not be possible to do the equivalent of Hibernate's addSynchronizedQuerySpace()
, addSynchronizedEntityClass()
and addSynchronizedEntityName()
using pure JPA.
What JPA however does allow you to do is to unwrap
a JPA Query
object to gain access to the JPA provider's API. If you're using Hibernate as a JPA provider, this will then allow you to use Hibernate's addSynchronizedXxx
methods as follows:
Query query = entityManager.createNativeQuery("UPDATE user SET ...");
query.unwrap(org.hibernate.SQLQuery.class)
.addSynchronizedEntityClass(User.class);
It's not an ideal solution, but it will effectively allow you to prevent the entire second level cache from being invalidated.
Upvotes: 8