Sunil Dabburi
Sunil Dabburi

Reputation: 1472

Will Cache Query work on itself? JPA Cache Eclipselink

I have a simple question on JPA Cache. I created a named query for a persistence unit named "Service" like below:

@NamedQuery(name = DBConstants.ALL_SERVICES, query = "select s from Service s",
            hints = {
                    @QueryHint(name = QueryHints.QUERY_RESULTS_CACHE, value = HintValues.TRUE),
                    @QueryHint(name = QueryHints.QUERY_RESULTS_CACHE_SIZE, value = "200")
            }),

The above code lets JPA cache store up-to 200 result entries. Now, when I perform a sub-query like "Select s from Service s where s.name='abc'", what would happen?

Will it run this query on the cached entries OR would it pass it to database to process the query? Thanks for your support.

Upvotes: 0

Views: 169

Answers (1)

Chris
Chris

Reputation: 21145

I think you are confusing different levels of caching, and the 200 value you are using is not the number of entities, but the number of query executions that are stored. See q_query-results-cache_size.htm for details, as the 200 value you are using should be set to 1 - you aren't going to execute this query with different parameters, so only one result will ever need to be cached

Your query hints setup a query cache for that particular query: The query cache means results from that specific query are cached. In this case, if you execute your DBConstants.ALL_SERVICES query the first time, it will bring in all Service results from the database. On the next execution of DBConstants.ALL_SERVICES, it will check the query cache and see it has been executed, and return the same exact results. These entity results will also be placed in the entity caches: the first and second level (EM and EMF) caches.

If you execute a different query, it would need or use its own query cache, independent of the one setup for DBConstants.ALL_SERVICES. There isn't one by default, so it will go to the database each time, return the appropriate rows, and then hit the 1st level cache (EntityManager) and/or 2nd level cache for entities if they are already built. If any are not, it will build them and put them in the appropriate entity caches.

I find this a good resource to describe caching in JPA

Upvotes: 2

Related Questions