简体   繁体   中英

Hibernate Session.multiLoad L2 cache issue

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?

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

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);

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