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();
QueryHints.CACHE_USAGE
withCacheUsage.CheckCacheThenDatabase
caused my list query to return only one entry. Works correctly with @André Luiz Cardoso's answer. – Haun