缓存默认的Spring Data JPA方法

时间:2013-11-03 12:34:59

标签: spring hibernate jpa caching spring-data-jpa

任务:使spring jpa数据的基本方法可以缓存(使用hibernate / jpa),比如

Page<T> findAll(Pageable pageable)
List<T> findAll();
etc

并且在某种顶级通用接口级别上执行,没有自定义dao实现。

这是原始主题的延续 How to add QueryHints on Default Spring Data JPA Methods?

我还没有找到解决方案,但尝试用不同的方式解决它,包括添加注释等 @javax.persistence.Cacheable@org.hibernate.annotations.Cache 关于数据模型类。


以下是我的配置摘录:

  1. pom.xml(取自here):

    ...
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.1.9.Final</version>
        <exclusions>
            <exclusion>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.7.0</version>
    </dependency>
    ...
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.4.2.RELEASE</version>
    </dependency>
    ...
    
  2. 的applicationContext.xml:

    <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>     
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="persistenceUnitName" value="persistenceUnit"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
  3. 的persistence.xml:

    ...
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
        ...
        <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
        <property name="hibernate.cache.use_second_level_cache" value="true"/>
        <property name="hibernate.cache.use_query_cache" value="true" />
    </properties>
    ...
    
  4. 除了上述所有内容之外,我已经配置了spring 3.2缓存,但最终我想要一个不基于spring缓存的解决方案,所以目前我还没有使用spring cache config。

  5. 我的模型如下:

    @Entity
    @Table(name = "ABC")
    @Cacheable(true)
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class ABC {
    ...
    
  6. 我的父通用DAO看起来像:

    public interface CacheableGenericDao<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
        List<T> findAll();
        Page<T> findAll(Pageable pageable);
        <S extends T> S save(S entity);
        ...
    

  7. P.S。这是关于该主题的另一个有用的link,但我确实想要使用基本的方法名称。

    那么我在概念上错过了什么?是否有任何方法或我是否想要太多?

1 个答案:

答案 0 :(得分:0)

这就是事情的发展方向:jira.springsource.org/browse/DATAJPA-173