Ehcache Layer 2 Cache not working with JPA and Hibernate?

EDIT: I have to say that I have been studying this for a couple of days - there is a lot of information on how to configure ehcache with Hibernate, but basically they do not refer to the use of JPA and annotations - they either refer to pure Hibernate, or to configuration via XML . (I just want to clarify that I was already on the Internet on this issue.) I use JPA and annotations, so most of these setup guides relate to files that I don’t have in my application (for example, hbm.xml files).

I have an application using Hibernate 3.6.10.FINAL, Spring Data 1.3.2.RELEASE and Spring version 3.2.1.RELEASE. I am trying to get second level caching, working in sleep mode. According to the documentation, I can do this by simply including the following dependency and configuration:

(POM.XML)

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

(persistence.xml)

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

I annotated one of my entity classes using the javax.persistence.Cacheable annotation and tried to view the statistics in a JUnit test:

public void cacheTest() {
    RandomDataGenerator randomData = new RandomDataGenerator();
    for (int i = 0; i < 10; i++) {
        AppMaster master = masterService.findOne(randomData.nextLong(1, 10));
        logger.debug(String.format("Read one record back = %1$d, %2$s", master.getApplicationId(), master.getApContact()),AppMasterServiceTest.class);
        //  Get statistics from hibernate session
        Session session = (Session)masterService.getEntityManager().getDelegate();
        Statistics statistics = session.getSessionFactory().getStatistics();
        logger.debug(String.format("Second level stats = %1$d, %2$d, %3$d", 
                statistics.getSecondLevelCachePutCount(), 
                statistics.getSecondLevelCacheHitCount(),
                statistics.getSecondLevelCacheMissCount()), AppMasterServiceTest.class);
    }

But statistics are always zero.

2013-11-11 11:20:33,908 DEBUG [main] test.service.AppMasterServiceTest  - Second level stats = 0, 0, 0

Can someone help me diagnose this?

+4
source share
1 answer

javax.persistence.Cachable , ENABLE_SELECTIVE persistence.xml. , :

<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

http://docs.oracle.com/javaee/6/api/javax/persistence/Cacheable.html

: @Cacheable JPA2 @Cache Hibernate

+3

All Articles