I am migrating a legacy system that performs a number of repetitive queries by immutable composite business keys. While I am using surrogate keys in the migrated database, to boost performance, I setup natural id mapping, a query cache and second level cache as described in the hibernate documentation, section 15.9, Queries by natural identifier (Critera query, using Restrictions.naturalId()). This worked as adverised, the second and later queries being pulled from the cache’s without any database access, even when the non-natural id attributes were updated.
However, when I tried to apply the technique farther, I ran into an issue. In many cases, the application runs repeated queries over a partial set of the composite natural identifier, which are used to obtain a list of related records. Using criteria queries with restrictions worked well for these too, intitially, as repeated queries did not hit the database. However, a problem came in when a new entity was inserted with the same partial key. The cached query was not invalidated, so when the query was run again, it returned the original result set from the query cache, which did not include the newly inserted record.
First Question
It was unclear from the documentation if this is the intended behavor. The documenation states “However, there is one special kind of query where we can optimize the cache invalidation algorithm: lookups by a constant natural key.” This implies there is still a cache invalidation routine, but doesn’t indicate what it is.
My natural keys are constant and immutable. Should the query cache be invalidated on insert of a new record that matches a partial natural key?
Second Question
If Hibernate does not automatically invalidate the cache on insert of a related record, is their a API I can use to do so manually in my DAO on an insert operation? I couldn’t see any command to programatically access the query cache.
Example
I have a entity with three immutable natural ids: City, Family, Member. A common query is by City and Family to retrive all members of the family. Members are usually defined when the family is added, and all keys are immutable. However, in some rare cases, a new member is added to an existing family. If there is a query existing is the cache to retrieve all members by city at the time of the insert, then after the insert, requesting all members again does not appar to include the newly added member.
Note that I have searched the forums on query cache natural id, and haven't seen a post that applied. I rearched the online documenation, and read the applicable sections in Java Persistance with Hibernate. I have not included code because I am not looking for a specific fix, just general information.
Thank you in advance for your attention
J.A. Simons.
|