JPA使用ehcache开启二级缓存

一、pom.xml


<dependency>
  <groupId>net.sf.ehcachegroupId>
  <artifactId>ehcache-coreartifactId>
  <version>2.6.9version>
dependency>
<dependency>
  <groupId>org.hibernategroupId>
  <artifactId>hibernate-ehcacheartifactId>
  <version>${hibernate.version}version>
dependency>    

二、ehcache.xml

xml version="1.0" encoding="UTF-8"?>
<ehcache>

<defaultCache 
    maxElementsInMemory="1000"
    eternal="false"
    timeToIdleSeconds="1200"
    timeToLiveSeconds="1200"
    overflowToDisk="false"
    clearOnFlush="true">
defaultCache>


ehcache>

三、applicationContext.xml

        
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
        <property name="packagesToScan" value="com.mushi.core" />
        <property name="jpaProperties">
            <props>
                
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategyprop>
                
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hibernate.format_sql">falseprop>
                
         
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactoryprop> <prop key="hibernate.cache.use_second_level_cache">trueprop> <prop key="hibernate.cache.use_query_cache">trueprop> props> property> bean>

四、在dao中添加注解

    @Query("select user from User user ORDER BY user.createtime DESC")
    @QueryHints({@QueryHint(name = "org.hibernate.cacheable", value ="true") })
    List getAll();

使用@QueryHints注解 令查询方法使用查询缓存

五、在类中定义

@Entity
@Table(name = "DAE_USER")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User extends ObjectEntity{
}

 

 

 

外:默认情况下二级缓存只会对load get 之类的方法缓存, 想list iterator 之类的方法也使用缓存 必须跟查询缓存一起使用, 重写查询方法 例如:

return (User) getCurrentSession().createQuery(hql).setCacheable(true).uniqueResult();

转载于:https://www.cnblogs.com/sishishinn/p/5474398.html

你可能感兴趣的:(java)