Question

We need to cache the results of a query; the query returns the whole table of a database. The problem is that the database is changed externally by other application; the Java application making the query is notified with the exact primary key of the row changed.

Is it possible to replace only the changed element from the query cache, not the whole list? Is this the 1st level cache (from EntityManager) 2nd level Cache (from EntityManagerFactory) or a different cache?

If it is possible can this be done from JPA?

entityManager.refersh(entity);

or is this query cache the 2nd level JPA cache:

entityManagerFactory.getCache().evict(cls, primaryKey);

or only possible through Hibernate/EclipseLink API?

If is not possible, in order to achieve this, would calling entityManager.find() on all elements do it?

I haven't find anything useful neither in Hibernate documentation nor in EclipseLink documentation. Hibernate supports regions and refreshing only regions, but we need entity-level refresh granularity.


Later edit to clarify my findings.

Following the link posted by @Chris in the comment I have found out that what I wanted is actually supported by EclipseLink but only for Oracle Database (there is possible to implement own handler for other vendors; but the call from database is not standardized and differs from vendor to vendor). I have not found if Hibernate supports this or not.

Anyhow the query cache from EclipseLink had some very poor performance compared with Spring Cache (based on CocurrentMap) or with custom based cache so will remain with Spring Cache or Custom Cache over Spring Jdbc.

Was it helpful?

Solution

EntityManager.refresh() is what you want - it refreshes the entity from what is in the database. This should also update the entity in the shared cache if you are not in a transaction, otherwise you may need to use the entityManagerFactory.getCache().evict(cls, primaryKey); as well to clear the second level shared cache so it can be read into it as well later on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top