简体   繁体   中英

Efficient cache-aware fetching of multiple entities given their ids

This is JPA2 running on Hibernate.

I want to retrieve multiple instances of the same entity type, given their ids. Many of them will already be in the persistence context and/or second-level cache.

I tried several approaches, but all seem to have their drawbacks:

  • When I iterate over the ids with entityManager.find(id) , I get one query for each non-cached item, that is, too many queries.
  • With a query of the form SELECT e FROM MyEntity e WHERE e.id in (:ids) , the cached entries will be reloaded from the db.
  • I can manually check the cache beforehand for each of the ids using entityManager.getEntityManagerFactory().getCache().contains(id) . This works for the second-level cache, but will return false on entries that are in the persistence context, but not in the second-level cache.

What is the best way of doing this without choosing between loading inefficiently and loading too much?

You should* be able to speculatively pull an entity out of the session cache like this:

T obj = entityManager.getReference(entityClass, id);
boolean inSessionCache = entityManager.getEntityManagerFactory().isLoaded(obj);

This still leaves you with a pretty gross solution, i admit.

(* might)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM