Hibernate Session.multiLoad L2 cache issue

552 views Asked by At

I'm using Hibernate 5.2.6 with the configured L2 cache (via jhache/ehcache). I want to load multiple entities by id

session.byMultipleIds(User.class).multiLoad(ids)

After the first call is see

select user0_.id as id1_20_0_ ... from user_data user0_ where user0_.id in (?,...,?)

in the log and User entities are placed to the L2 cache.

The second call triggers the same SQL statement in the log and isn't retrieving entities from L2 cache.

With the L1 cache this issue doesn't occur (with enableSessionCheck(true)).

Is it expected behavior or I've misconfigured something?

2

There are 2 answers

0
Barnaby On

This has now been fixed in with https://hibernate.atlassian.net/browse/HHH-12944 which is available in Hibernate 5.4.0.CR1.

Detailed documentation can be found at http://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#pc-by-multiple-ids.

Assuming you want Users identified by 1L, 2L, and 3L you can now use:

session.byMultipleIds(User.class).enableSessionCheck(true).multiLoad( 1L, 2L, 3L);
0
Maksim Prabarshchuk On

I've worked it around with helper class:

public class HibernateUtils {

    static <T> List<T> byMultipleIds(Session session, Long[] ids, Class<T> entityClass) {
        List<Long> notCached = new ArrayList<>();
        for (Long id : ids) {
            if (!session.getSessionFactory().getCache().contains(entityClass, id)) {
                notCached.add(id);
            }
        }
        return session.byMultipleIds(entityClass).enableOrderedReturn(false).withBatchSize(ids.length).multiLoad(notCached);
    }

}

But it doesn't looks like good solution