在Springboot + JPA存储库中使用二级缓存

时间:2015-11-27 08:10:35

标签: spring-boot spring-data-jpa second-level-cache

我将Spring Boot配置用于主表的二级缓存。 我没有在Spring Boot中配置二级缓存。需要了解缓存的完成方式以及检索。

这是我的Application.java类(SpringBootServletinitializer)..我添加了一个测试方法allCodeValues(),只是为了验证我是否只获得一次hibernate查询。但是我看到查询被触发了两次,因此说存储库调用没有在hibernate中缓存。请帮我准确一下SpringBoot for EhCaching的配置......

@Bean(name = "entityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

     LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
     entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
     entityManagerFactoryBean.setDataSource(dataSource());
     entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
     entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

     return entityManagerFactoryBean;
 }


  private Properties jpaHibernateProperties() {

     Properties properties = new Properties();

     properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

     properties.put(PROPERTY_NAME_HIBERNATE_DIALECT,env.getProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
     properties.put(PROPERTY_NAME_HIBERNATE_HBM_AUTO,env.getProperty(PROPERTY_NAME_HIBERNATE_HBM_AUTO));    
     properties.put("spring.jpa.properties.hibernate.cache.use_second_level_cache", "true");
      properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
     properties.put("hibernate.cache.default_cache_concurrency_strategy", "NONSTRICT_READ_WRITE");
     properties.put("hibernate.cache.region_prefix", "valCache");
     properties.put("javax.persistence.sharedCache.mode", "ALL");

}

}

以下是JPA Persistence的配置

@Repository
public interface WorkflowListRepository extends JpaRepository<WorkFlowList, String>{


public List<WorkFlowList> getAllDocuments();
}

我使用JPARepository与实体进行通信...这里我使用WorklfowRepository来获取二级缓存中的数据..

@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "WORKFLOW_LIST")
@Access(AccessType.FIELD)
@NamedQuery(name="WorkFlowList.getAllDocuments",query = "from WorkFlowList work")
public class WorkFlowList implements in.vit.leasing.generic.entity.Entity<WorkFlowList>{
.......
}

在实体中,我添加了注释@Cacheable和@Cache,如下所示

EntityDeploy

0 个答案:

没有答案