【问题标题】:Hibernate second level cache, one to manyHibernate二级缓存,一对多
【发布时间】:2015-02-05 10:36:28
【问题描述】:

我第一次尝试根据不同的教程使用二级缓存,但它不起作用。我有课:

@Entity
@Table(name="TABLE_NAME")
@org.hibernate.annotations.Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Foo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;


@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Sentence> collection_name;

和我的 hibernate.cfg.xml 文件中的配置

 <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
 <property name="hibernate.cache.use_second_level_cache">true</property>
 <property name="hibernate.cache.use_query_cache">true</property>

我打开了

<property name="show_sql">true</property>

我认为第二个查询不会命中数据库,但确实如此。

我的查询:

  List<Foo> result = session.createQuery("select p from Foo p order by size(p.collection_name) desc ").list();

怎么了?

【问题讨论】:

    标签: java hibernate caching ehcache


    【解决方案1】:

    如果你想缓存你的 HQL 查询结果,你必须检测你的查询:

    List<Foo> result = session
                          .createQuery("select p from Foo p order ... ")
                          .setCacheable(true)
                          .list();
    

    另外,您可以告诉 Hibernate,它应该使用哪个缓存配置(缓存区域):

    List<Foo> result = session
                          .createQuery("select p from Foo p order ... ")
                          .setCacheable(true)
                          .setCacheRegion("foo_region")
                          .list();
    

    当然,全局设置hibernate.cache.use_query_cache必须设置为true

    实体类上的@Cache注解用于在通过ID获取单个实体时缓存单个实体

    Foo foo = session.get(Foo.class, fooId);
    

    【讨论】:

      【解决方案2】:

      在 foo.java 和 Sentence.java 中都指定

      @Cacheable
      @Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
      

      也只是在 @OneToMany 注释指定之后

      @Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
      

      如果您使用的是查询对象:

      Query q 
      enable the cacheable to true
      

      【讨论】:

        猜你喜欢
        • 2015-05-14
        • 2020-03-26
        • 2010-11-16
        • 2014-11-28
        • 2011-12-18
        • 2012-12-12
        • 2016-05-10
        • 2014-03-15
        • 2010-10-16
        相关资源
        最近更新 更多