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:
entityManager.find(id)
, I get one query for each non-cached item, that is, too many queries. SELECT e FROM MyEntity e WHERE e.id in (:ids)
, the cached entries will be reloaded from the db. 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.