jpa, hibernate 和 spring 时配置 ehcache 二级缓存的步骤。

在 JPA、Hibernate 和 Spring 中配置 Ehcache 缓存

 jpa, hibernate 和 spring 时配置 ehcache 二级缓存的步骤。

缓存配置

首先在 persistence.xml 配置文件中添加下面内容:

<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
<property name="hibernate.generate_statistics" value="true"/>

 

 

EHCache 还需要一些独立的配置,你需要在类路径中放置 ehcache.xml ,文件内容如下:

1
2
3
4
5
6
<cache name= "samples.Employee"
            maxElementsInMemory= "2000"
            eternal= "false"
            timeToIdleSeconds= "1800"
            timeToLiveSeconds= "3600"
            overflowToDisk= "false" />

  

实体配置

在映射实体类中声明注解

1
@org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)

 

现在,你已经为一个对象配置了缓存,例如通过类似 loadById 之类的方法就可以使缓存生效,但当需要一些查询或者使用标准查询对象时默认是不使用缓存的,因此我们需要在代码上做一些处理。

查询缓存

为了启用查询缓存,我们需要两个配置,一个是启用 hibernate.cache.user_query_cache,另外一个是设置查询缓存:

1
2
3
Query query = entityManager.createQuery( "from " + Employee. class .getName());
query.setHint( "org.hibernate.cacheable" , true );
return query.getResultList();

  

通过统计来确保缓存起效

执行下面的代码可以打印缓存的统计信息

1
2
3
4
5
EntityManagerFactoryInfo entityManagerFactoryInfo =
(EntityManagerFactoryInfo) applicationContext.getBean( "entityManagerFactory" );
EntityManagerFactory emf = entityManagerFactoryInfo.getNativeEntityManagerFactory();
EntityManagerFactoryImpl emfImp = (EntityManagerFactoryImpl)emf;
System.out.println(emfImp.getSessionFactory().getStatistics());

  

别忘了,上述代码需要在 persistence.xml 中启用 hibernate.generate_statistics

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值