Question

I have an entity (JPA annotations with Hibernate query interface) which has a composite business key of two properties (an external-id and a subsidiary-id [that's a foreign key]) and a primary db key.

I have a JavaSE multi-threaded process which runs "with respect to a subsidiary" and needs to query/update/insert those entities using that composite key (it gets datasets of those external-ids).

I can guarantee that once such a process loads no other process will try to insert/update/remove that subsidiary.

What I want is to load all existing entities of that subsidiary on startup and then have every query for a pair of [externalId,subsidiaryId] to go through the cache and only if there's a miss to go through the db. In case one of the threads from the process inserts an entity I of course want that to be added to that cache.

What's the best course of action?

I know there's query caching but from what I can gather that will still be a miss the first time of every [externalId,subsidiaryId] pair.

Thanks and if there's anything which I'm not clear about please ask

Update
I had to stop investigating this issue but now that I've come back to it I think that it's seems reasonable that only the query cache and JB Nizet's answer are the only ones applicable.
I'll accept JB Nizet's answer as it is interesting and I might use it (not sure yet).

Était-ce utile?

La solution

I would use a second-level cache for the entity, query for all the subsidiry's entities at startup (this will fill the second-level cache), and initialize an application cache which would just map [externalId, subsidiaryId] to [id].

Then, each time you're searching for an entity with a given [externalId, subsidiaryId], first get its ID from the application cache, then

  • if the ID is not in the cache, execute the query, update the application cache, and return the found entity
  • if the ID is in the cache, get the entity using its ID, which will go to the second-level cache and avoid hitting the DB
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top