Search code examples
performancejpajava-ee-6ejb-3.1glassfish-4

@NamedQuery cachable result alternative


I'm using @NamedQuery to get some results from my DataBase. After manipulating it for a while, I understood that the @NamedQuery is requested once the application is deployed & stored it in the cache for more performance.

So, I'm searching for a way(kind of query) that get always the information from database when the request is made, so I can get always updated data ? And if there is a way to do such a thing, what is its performance ?


Solution

  • As outlined already in the comments, you have misunderstanding of the NamedQuery. Not the result is stored in cache, but the query SQL is.

    Nevertheless sometimes the EntityManager caches some things and I guess you need a solution for that....

    If you are working with Query objects (e.g. EntityManager.createNamedQuery("nameOfYourQuery")) and EclipseLink then you can do the following:

    Query query = EntityManager.createNamedQuery("nameOfYourQuery");
    query.setHint(QueryHints.REFRESH, HintValues.TRUE);
    query.getResultList();
    

    You can also setup query hints directly in the NamedQuery like this:

    @NamedQuery(name = "something", query = "SELECT n FROM something",
     hints=@QueryHint(name=QueryHints.REFRESH, value=HintValues.TRUE))
    

    Another way with query hints would be this one:

    query.setHint(QueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);
    

    For a list of possible query hints, have a look at the EclipseLink docs.

    If you want to completely deactivate database result caching you can also try the following in your persistence.xml:

    <property name="eclipselink.query-results-cache" value="false"/>