I need to efficiently load a large number of entities based on a list of ad hoc IDs. Unfortunately it doesn’t look like the 2nd level cache is checked first when making Restrictions.In(Projections.Id(), ids) criteria queries.
I guess I’m looking for something similar to ISession.Load that takes a collection of IDs (instead of just one) and only execute an IN query for entities that can’t be found in either the 1st or 2nd level caches. If nothing like this exists then what’s the easiest way to check the two caches manually without resorting to reflection?
Darren Kopp‘s comment is absolutely right, batching automatically handles this provided you remember to use
ISession.Loadinstead ofISession.Getand you don’t touch any of the proxy objects until you’ve finished fetching them all.However I thought I’d share another novel solution I came up with for environments that don’t have lazy loading or batching enabled. By subclassing the
DefaultLoadEventListenerclass and returning null from theLoadFromDatasourcemethod it’s possible to load an entity if it exists in the 1st or 2nd level caches without touching the database. It’s then a simple matter of fetching the missing entities in a single IN query and weaving them into an ordered collection of results.Here’s the very simple
LoadHelperclass that does the heavy lifting: