Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether an entity already exists in the Hibernate session cache given an entity ID?

Tags:

hibernate

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);
}
like image 590
Ken Joyner Avatar asked Nov 01 '22 00:11

Ken Joyner


1 Answers

You may use Session.getStatistics(), and then analyze EntityKeys set taken from SessionStatistics.getEntityKeys().

like image 193
Eugene Avatar answered Nov 15 '22 10:11

Eugene