【问题标题】:Hibernate second level cache exampleHibernate 二级缓存示例
【发布时间】:2017-12-04 21:38:36
【问题描述】:

我正在开发hibernate + ehcache程序。

@Entity
@Table(name = "pizza")
public class Pizza implements Serializable{
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private double price;

    public long getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

}

ehcache.xml

  <cache name="com.abp.osp.domain.Pizza"   
maxElementsInMemory="100"   
eternal="false"   
timeToIdleSeconds="5"   
timeToLiveSeconds="200" /> 
</ehcache>

我在 bean.xml 中提到过 ehcache

   <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
        <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">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
         <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>

我在 dao 类中的调用方法是

 Session session1=sessionFactory.openSession();  

          Pizza pizza2=(Pizza)session1.load(Pizza.class, 2);
          System.out.println("pizza2--"+pizza2.getName());  
          session1.close(); 

 Session session2=sessionFactory.openSession();  

          Pizza pizza4=(Pizza)session2.load(Pizza.class, 2);
          System.out.println("pizza4--"+pizza4.getName());  
          session2.close(); 

输出是:

Hibernate: select pizza0_.id as id0_0_, pizza0_.name as name0_0_, pizza0_.price as price0_0_ from pizza pizza0_ where pizza0_.id=?
pizza2--Thin Crust
Hibernate: select pizza0_.id as id0_0_, pizza0_.name as name0_0_, pizza0_.price as price0_0_ from pizza pizza0_ where pizza0_.id=?
pizza4--Thin Crust

但它在数据库中命中两次。我的代码中没有发现任何错误。请告诉我为什么它在数据库中命中两次。

【问题讨论】:

    标签: hibernate ehcache


    【解决方案1】:

    我已经解决了我的问题。我需要添加

    @Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="pizza")
    

    在域类中。

    @Entity
    @Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="pizza")
    @Table(name = "pizza")
    public class Pizza implements Serializable{
    

    【讨论】:

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