Multiload from cache


I want to multiload entities by id. If those entities are in the cache, I want to load them from the cache.

As I understand it, the following code won’t do that; it will instead return a null entry in the list for cached entities:

       List<?> result = session
// note, this will add null to the returned list, in place of cached entries, so we will have to fill them in
// this is true by default, but adding it to be explicit

Edit: the 5.4 documentation suggests a cached entity will be added to the list:

enableSessionCheck(boolean enabled)

This setting, which is disabled by default, tells Hibernate to check the first-level cache (a.k.a Session or Persistence Context) first and, if the entity is found and already managed by the Hibernate Session , the cached entity will be added to the returned List , therefore skipping it from being fetched via the multi-load query.

The javadoc comments are a bit more ambiguous:

	 * Specify whether we should check the {@link Session} to see whether the first-level cache already contains any of the
	 * entities to be loaded in a managed state <b>for the purpose of not including those
	 * ids to the batch-load SQL</b>.
	 * @param enabled {@code true} enables this checking; {@code false} (the default) disables it.
	 * @return {@code this}, for method chaining

As I understand it, were I to set .enableSessionCheck(false), entities in the cache would be fetched from the underlying persistent storage (the db), and not from the cache.

How do I do a multi-load that fetches entities from the cache if available, and from the underlying persistent storage (the db) for those not in the cache?


Edit: so the code I have should pull from the cache? What about the second-level cache?