Query caching with JPA 2.1

Hi there,

I’m trying to set up both query caching (and eventually second level caching) purely with JPA 2.1, and not with any hibernate-specific configuration, in a JavaEE 7 environment.

In my persistence.xml <persistence-unit> I have:


In my @Cacheable entity I have the class annotation:

@NamedQuery( name = "Thing.findByName", query = "SELECT t FROM Thing t WHERE t.name = :name")

And finally in my calling context I have:

em.createNamedQuery("Thing.findByName", Thing.class)
                .setParameter("name", name)

But each hit on the above query is still querying to the database. Is there anything I’m missing?

Also, is it true that query caching isn’t worthwhile in a clustered environment?

Finally, would using query caching make it so that I can eventually use JPA’s second level cache for lookups that aren’t simply by ID, since the query cache is getting a list of IDs for me?


There is no way you can use the second-level cache only with JPA-specific annotations because you need to set the cache concurrency strategy.

Check out this article for more details about using the Hibernate query cache.

That’s too bad.

Should query caching be doable with the details mentioned above?

Should query caching be doable with the details mentioned above?

I’m not sure what do you mean with “details mentioned above”.

Query Cache works only if you explicitly activate it using:

  • the hibernate.cache.use_query_cache configuration property
  • the org.hibernate.cacheable JPA query hint on every cacheable query