I would like to efficiently load multiple entities from the DB while taking advantage of the hibernates session cache (1st level cache not 2nd level). I was trying to do something like the following:
List<T> getEntities(Class<T> clazz, Collection<Long> ids) {
ArrayList<T> result = new ArrayList<T>(ids.size());
for (Long id : ids) {
if (session.containsEntity(clazz, id))
result.add((T) session.get(clazz, id));
else
idsToFetch.add(id);
}
if (CollectionUtils.isNotEmpty(idsToFetch)) {
List<T> fetchedEntities =
session.createCriteria(clazz).add(Restrictions.in("id", idsToFetch)).list();
result.addAll(fetchedEntities);
}
return results;
}
The problem with the above is that containsEntity does not exist in the session class. When I look at it in the debugger, I see the information within the class (in the persistentContext class), I just can see how to get at it.
-- Update: Here was the solution I used after reading the answer, not sure if there is a better one or not
ClassMetadata metadata = _sessionFactory.getClassMetadata(clazz);
SessionImpl session = (SessionImpl) _sessionFactory.getCurrentSession();
EntityPersister persister = session.getFactory().getEntityPersister(metadata.getEntityName());
PersistenceContext context = session.getPersistenceContext();
List<Serializable> idsToFetch = new ArrayList<Serializable>(ids.size());
for (Serializable id : ids) {
EntityKey entityKey = new EntityKey(id, persister, EntityMode.POJO);
T entity = (T) context.getEntity(entityKey);
if (entity != null)
result.add(entity);
else
idsToFetch.add(id);
}
You may use Session.getStatistics(), and then analyze EntityKeys set taken from SessionStatistics.getEntityKeys().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With