在 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 ,文件内容如下:

<cache name="samples.Employee"
           maxElementsInMemory="2000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="3600"
           overflowToDisk="false"/>

  

实体配置

在映射实体类中声明注解

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

 

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

查询缓存

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

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

  

通过统计来确保缓存起效

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

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

原文地址:https://www.cnblogs.com/nsw2018/p/6530762.html