未从休眠/ehcache 二级缓存读取的集合



我正在尝试在Spring项目中使用ehcache/hibernate缓存延迟加载的集合。当我执行session.get(Parent.class,123)并多次浏览子项时,每次都会执行查询以获取子项。父级仅在第一次查询,然后从缓存中解析。

可能我错过了一些东西,但我找不到解决方案。请参阅下面的相关代码。

我正在使用 Spring (3.2.4.RELEASE) Hibernate(4.2.1.Final) 和 ehcache(2.6.6)

父类:

@Entity
@Table(name = "PARENT")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, include = "all")
public class Parent implements Serializable {
/** The Id. */
    @Id
    @Column(name = "ID")
    private int id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    private List<Child> children;
    public List<Child> getChildren() {
        return children;
    }
    public void setChildren(List<Child> children) {
        this.children = children;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Parent that = (Parent) o;
        if (id != that.id) return false;
        return true;
    }
    @Override
    public int hashCode() {
        return id;
    }
}

子班:

@Entity
@Table(name = "CHILD")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, include = "all")
public class Child {
    @Id
    @Column(name = "ID")
    private int id;
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "PARENT_ID")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    private Parent parent;
    public int getId() {
    return id;
    }
    public void setId(final int id) {
    this.id = id;
    }
    private Parent getParent(){
        return parent;
    }
    private void setParent(Parent parent) {
         this.parent = parent;
    }
    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
    }
        final Child that = (Child) o;
        return id == that.id;
    }
    @Override
    public int hashCode() {
        return id;
    }
}

应用程序上下文:

 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>Parent</value>
            <value>Child</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
            <prop key="hibernate.connection.charSet">UTF-8</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.use_sql_comments">true</prop>
            <!-- cache settings ehcache-->
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
            <prop key="hibernate.generate_statistics">true</prop>
            <prop key="hibernate.cache.use_structured_entries">true</prop>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.transaction.factory_class"> org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</prop>
            <prop key="hibernate.transaction.jta.platform"> org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform</prop>
        </props>
    </property>
</bean>

我正在运行的测试用例:

@Test
public void testGetParentFromCache() {
  for (int i = 0; i <3 ; i++ ) {
      getEntity();
  }
}
private void getEntity() {
    Session sess = sessionFactory.openSession()
    sess.setCacheMode(CacheMode.NORMAL);
    Transaction t = sess.beginTransaction();
    Parent p  = (Parent) s.get(Parent.class, 123);
    Assert.assertNotNull(p);
    Assert.assertNotNull(p.getChildren().size());
    t.commit();
    sess.flush();
    sess.clear();
    sess.close();
}

在日志记录中,我可以看到第一次执行 2 个查询时获取父级并获取子级。此外,日志记录显示子实体以及集合存储在第二级缓存中。但是,在读取集合时,将执行查询以在第二次和第三次尝试时获取子项。

由于 EHCache 不起作用,我们也尝试了无限跨(具有不同的并发级别)。不幸的是,我们不断遇到同样的问题。

附言EHCache论坛也解决了这个问题:http://forums.terracotta.org/forums/posts/list/8785.page和冬眠论坛:https://forum.hibernate.org/viewtopic.php?f=1&t=1029899

此外,我的同事创建了一个类似于我们在GitHub上的项目设置和问题的示例项目:https://github.com/basvanstratum/cacheimpl

这里的问题在于你的Hibernate版本。下面的代码将解释这里出了什么问题。

public class DefaultInitializeCollectionEventListener
      implements InitializeCollectionEventListener {
  public void onInitializeCollection(InitializeCollectionEvent event)
        throws HibernateException {
    …
    final boolean traceEnabled = LOG.isTraceEnabled();
    …
    final boolean foundInCache = methodReturningTrueWhenInCache();
    if ( foundInCache && traceEnabled ) {
      LOG.trace( "Collection initialized from cache" );
    }
    else {
      if ( traceEnabled ) {
        LOG.trace( "Collection not cached" );
      }
      methodThatExecutesAQuery();
  }
}

这是Hibernate的JIRA票证的链接。解决方案是启用跟踪日志记录(哎呀 - 忘记我什至说过这个)或将您的库升级到版本 4.2.2 或更高版本。https://hibernate.atlassian.net/browse/HHH-8250

最新更新