Second level cache not working in Hibernate + Spring + JPA and EhCache
<p>Let me make my understanding clear for second level cache. There is a query in base class of my web application. This query is called for almost every action (I am using Struts and this is how application is designed so can't really mess with it), for example loading my home page calls three separate Struts actions and this query is executed for each action. The query in QueryDsl form looks like
 <code>Iterable&lt;Event&gt; eventsFromDb2 = eventRepository.findAll(EventExpressions.queryAllEvents());
</code>
and in simplified form it looks <code>Select e from Event e where e.deleted = false</code></p>

<p>This query takes it own sweet time of ~10sec so it makes the application quite slow because its called for every action(CRUD) of the web application. As per my understanding, on enabling second level cache, hibernate+ Spring orm should fetch the result from cache and avoid database request. However, it is not working. The persistence.xml looks like following  </p>

<pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
                       http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
                       http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                       http://www.springframework.org/schema/tx
                       http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"&gt;



&lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" depends-on="flyway"&gt;
    &lt;property name="dataSource" ref="dataSource" /&gt;
    &lt;property name="packagesToScan" value="de.mm.moreevent.type" /&gt;
    &lt;property name="jpaVendorAdapter"&gt;
        &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt;
            &lt;property name="showSql" value="false" /&gt;
            &lt;property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" /&gt;
            &lt;property name="generateDdl" value="true" /&gt;
        &lt;/bean&gt;
    &lt;/property&gt;
&lt;property name="jpaPropertyMap"&gt;
    &lt;map&gt;
        &lt;entry key="hibernate.cache.use_query_cache" value="true" /&gt;
        &lt;entry key="hibernate.cache.use_second_level_cache" value="true" /&gt;
        &lt;entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" /&gt;
        &lt;entry key="hibernate.cache.default_cache_concurrency_strategy" value="read-write" /&gt;
        &lt;entry key="javax.persistence.sharedCache.mode" value="ALL" /&gt;
        &lt;entry key="hibernate.generate_statistics" value="false" /&gt;
    &lt;/map&gt;
&lt;/property&gt;
&lt;/bean&gt;

&lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
&lt;!-- see: http://springcert.sourceforge.net/2.5/4-study-transaction-management.html --&gt;
&lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt;
    &lt;tx:attributes&gt;
        &lt;tx:method name="makeBooking" read-only="false" propagation="NESTED" rollback-for="de.mm.moreevent.exception.ManagerException" /&gt;
        &lt;tx:method name="sendConfirmationAndInvoice" read-only="true" propagation="NESTED" rollback-for="de.mm.moreevent.exception.ManagerException" /&gt;
        &lt;tx:method name="sendConfirmationOnly" read-only="true" propagation="NESTED" rollback-for="de.mm.moreevent.exception.ManagerException" /&gt;
        &lt;tx:method name="saveOrUpdate" read-only="false" propagation="NESTED" rollback-for="de.mm.moreevent.exception.ManagerException" /&gt;
        &lt;tx:method name="participantsImport" read-only="false" propagation="NESTED" rollback-for="de.mm.moreevent.exception.ManagerException" /&gt;
    &lt;/tx:attributes&gt;

&lt;/tx:advice&gt;
&lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt;
    &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt;
    &lt;qualifier value="transactionManager" /&gt;
&lt;/bean&gt;

&lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt; &lt;!-- class="org.springframework.jdbc.datasource.DriverManagerDataSource" --&gt;
    &lt;property name="driverClass"&gt;
        &lt;value&gt;org.postgresql.Driver&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="jdbcUrl"&gt;
        &lt;value&gt;jdbc:postgresql://127.0.0.1:port/dbName&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="user"&gt;
        &lt;value&gt;user1&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="password"&gt;
        &lt;value&gt;******&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="initialPoolSize" value="5" /&gt;
    &lt;property name="minPoolSize" value="5" /&gt;
    &lt;property name="maxPoolSize" value="30" /&gt;
    &lt;property name="idleConnectionTestPeriod" value="200" /&gt;
    &lt;property name="acquireIncrement" value="1" /&gt;
    &lt;property name="maxStatements" value="0" /&gt;
    &lt;property name="numHelperThreads" value="3" /&gt;
&lt;/bean&gt;

&lt;!-- see: http://flywaydb.org/documentation/api.html  --&gt;
&lt;bean id="flyway" class="com.googlecode.flyway.core.Flyway" init-method="migrate"&gt;
    &lt;property name="dataSource" ref="dataSource" /&gt;
     &lt;property name="table" value="schema_version"&gt;&lt;/property&gt;
     &lt;property name="locations" value="customer/db-scripts/migration"/&gt;
&lt;/bean&gt;


&lt;bean id="bouncyCastleProviderInitialisation" class="de.mm.moreevent.util.BouncyCastleProviderInitialisation" init-method="init" /&gt;

&lt;bean id="strongEncryptorBC" class="org.jasypt.encryption.pbe.PooledPBEStringEncryptor"&gt;
    &lt;property name="providerName"&gt;
        &lt;value&gt;BC&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="algorithm"&gt;
        &lt;value&gt;algo&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="password"&gt;
        &lt;value&gt;******&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="poolSize"&gt;
        &lt;value&gt;4&lt;/value&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;bean id="hibernateStringEncryptor" class="org.jasypt.hibernate4.encryptor.HibernatePBEStringEncryptor"&gt;
    &lt;property name="registeredName"&gt;
        &lt;value&gt;strongHibernateStringEncryptor&lt;/value&gt;
    &lt;/property&gt;
    &lt;property name="encryptor"&gt;
        &lt;ref bean="strongEncryptorBC" /&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</code></pre>

<p></p>

<p>Following is Ehcache.xml</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
     name="cacheManager"
     updateCheck="false"
     maxBytesLocalHeap="100M"
     statistics="true"&gt;

&lt;!--
 | Please see http://ehcache.sourceforge.net/documentation    /configuration.html for
 | detailed information on how to configurigure caches in this file
 +--&gt;
&lt;!-- Location of persistent caches on disk --&gt;
&lt;diskStore path="java.io.tmpdir/moreEventObjCache" /&gt;

&lt;defaultCache eternal="false" maxElementsInMemory="100000"
    overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="600"
    timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" statistics="true"/&gt;

&lt;cache name="bookingTransaktions" eternal="true"
    overflowToDisk="false" diskPersistent="false"
    timeToIdleSeconds="0" timeToLiveSeconds="0" statistics="true"/&gt;

&lt;cache name="mailingBean" eternal="true" maxElementsInMemory="10000"
    overflowToDisk="false" diskPersistent="false"
    /&gt;
</code></pre>

<p></p>

<p>Following is my Entity class </p>

<pre><code>import javax.persistence.Cacheable;
...    
@Entity 
@Table(name = "EVENT")
@Cacheable
@Configurable(dependencyCheck = true)
public class Event extends MoreEventDataBaseEntity implements CloneChangeEventI {
...
</code></pre>

<p>I am testing for time taken to execute the query, following is the code(I am calling same query two times consecutively )</p>

<pre><code>    timer.mark();
    Iterable&lt;Event&gt; eventsFromDb = eventRepository.findAll(EventExpressions.queryAllEvents(), EventExpressions.orderByOnlineStartDate(true));
    timer.mark();
    Iterable&lt;Event&gt; eventsFromDb2 = eventRepository.findAll(EventExpressions.queryAllEvents(), EventExpressions.orderByOnlineStartDate(true));
    eventsFromDb2.getClass();
    timer.mark();
</code></pre>

<p>Now, in the result, this code snippet is called three times from web page and following is the result in the console</p>

<pre><code>init Struts page load: 
EventManager.java:130: +0ms

// Query fired first time, it took 8 seconds as expected  
EventManager.java:132: +8103ms
// Query fired second time, it took 15 ms due to so caching
EventManager.java:135: +15ms

init (Ajax1):
EventManager.java:130: +0ms
// Query fired and it took 9.5 sec, However I am expecting it to be few milliseconds ???? second level cache not working I suppose ????   
EventManager.java:132: +9501ms
EventManager.java:135: +21ms
Before timer 2016-09-09T14:21:41.853+02:00

init (Ajax2): 
EventManager.java:130: +1ms
???? took 9.5 seconds again. second level cache not working I suppose same as Ajax1????
EventManager.java:132: +9506ms
EventManager.java:135: +22ms
</code></pre>

<p>The same thing happens throughout the application. The second level cache is not working at all. This will be of great help for me if I can save this query execution time by caching. I am using Spring ORM 3.2.1, Hibernate EhCache 4.1.9 </p>