views:

1057

answers:

4

I have a collection of states, that I want to cache for the life of the application, preferably after it is called for the first time. I'm using EclipseLink as my persistence provider. In my EJB3 entity I have the following code:

@Cache
@NamedQueries({
    @NamedQuery(
        name = "State.findAll",
        query = "SELECT s FROM State s",
        hints = {
                @QueryHint(name=QueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheThenDatabase),
                @QueryHint(name=QueryHints.READ_ONLY, value=HintValues.TRUE)
            }
    )
})

This doesn't seem to do anything though, if I monitor the SQL queries going to MySQL it still does a select each time my Session Bean uses this NamedQuery.

What is the correct way to configure this query so that it is only ever read once from the database, preferably across all sessions?

Edit: I am calling the query like this:

Query query = em.createNamedQuery("State.findAll");
List<State> states = query.getResultList();
A: 

Just a guess here, but you might try

query.cacheQueryResults();

after you create it but before you getResultList.

-- MarkusQ

MarkusQ
Can you elaborate on how this would work? The JPA Query object does not support the cacheQueryResults() method. If I instead create a ReadObjectQuery I don't know how (or if I can) ask it for a list?
rustyshelf
If you don't want to use the eclipselink especific query, you have to use hints. It can be done through annotations, as Andre explained or through query.setHint(QueryHints.QUERY_RESULTS_CACHE, HintValues.TRUE)
Pau
A: 

I got EclipseLink 1.0.1 cache to work by adding just the query hint:

Query query = em.createNamedQuery("Person.find");
query.setParameter("NAME", name);      
query.setHint("eclipselink.cache-usage", "CheckCacheThenDatabase");
return (Person)query.getSingleResult();

I didn't change the entity at all, and haven't yet tried to configure cache using annotations.

tputkonen
A: 

do i have to use elipselink as a persistence provider to make eclipselink cache working, please advise

praveen
+1  A: 

The solutions posted here not worked for me. But i've made it work with:

@Cache
@NamedQueries({@NamedQuery(
      name = "State.findAll",
      query = "SELECT s FROM State s", 
      hints = {
          @QueryHint(name = QueryHints.QUERY_RESULTS_CACHE, value = HintValues.TRUE)
      }
    )})
André Luiz Cardoso
Exactly, QueryHints.CACHE_USAGE is for the use of second level cache. If you want query cache the hint you have to use is, as Andre said: QueryHints.QUERY_RESULTS_CACHE
Pau