Search code examples
jakarta-eejpaejbeclipselinkglassfish-3

How to get Glassfish/EclipseLink/JPA to cache entityManager.find results that return null


I though I had a problem where JPA/EclipseLink was not caching my entity objects in the L2 shared cache, because when I repeated a request I would get SQL statements hitting Derby. As I debugged this I discovered that the cache was working after all, what was happening was that just the entityManager.find requests for entities that did not exist (returning null) were not cached (no object to manage and keep in the cache in that case I imagine). Those requests were the ones getting to the database every time.

Is there a way to get the system (EclipseLink?) to "cache" the fact that previously requested keys do not exist so it can return null without hitting the database?

I'm using Glassfish version 3.1.2.1.


Solution

  • There is no guarantee that because something did not used to exist, that it will never exist. A common use case is to check if something exists, and if it does not create it, so you need to be careful in caching that something does not exist.

    There is not setting for this in EclipseLink in the object cache, but there is a setting in the query cache.

    If you define a named query for your find operation, you could then enable query caching for it. By default the query cache will cache a null result (this is configurable).

    http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Query_Cache