title: Hibernate Ehcache not using cached data
body: <p>I'm trying to get ehcache working in a non Spring environment (Swing Client with Hibernate Entity Manager).</p>
  
  <p>The cache seems to work, but for any reason the cache is sending all queries to the DB instead of using the cached values.</p>
  
  <p>But I don't know why.</p>
  
  <p>Any help will be appreciated.</p>
  
  <p>This is my environment:</p>
  
  <pre><code> &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
        &lt;version&gt;5.1.38&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate.common&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-commons-annotations&lt;/artifactId&gt;
        &lt;version&gt;4.0.4.Final&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
        &lt;version&gt;4.3.11.Final&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
        &lt;version&gt;3.5.6-Final&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
        &lt;version&gt;4.3.11.Final&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-ehcache&lt;/artifactId&gt;
        &lt;version&gt;4.3.11.Final&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
      &lt;/dependency&gt;
  </code></pre>
  
  <p>ehcache.xml</p>
  
  <blockquote>
  <pre><code> &lt;ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
              monitoring="autodetect" dynamicConfig="true"&gt;
  
           &lt;defaultCache
                  maxElementsInMemory="10000"
                  eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  overflowToDisk="false"
                  diskSpoolBufferSizeMB="30"
                  diskPersistent="false"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU"
                  /&gt;
      &lt;/ehcache&gt;
  </code></pre>
  </blockquote>
  
  <p>persistence.xml</p>
  
  <blockquote>
  <pre><code> &lt;?xml version="1.0" encoding="UTF-8" ?&gt;
      &lt;persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"&gt;
  
        &lt;persistence-unit name="jaccount" transaction-type="RESOURCE_LOCAL"&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Account&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.AccountId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Booking&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.BookingId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Category&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.CategoryId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Property&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Type&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Year&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.YearId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.I18n&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.I18nGroup&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.I18nItem&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Language&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.User&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.UserId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Payment&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.UserType&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.Customer&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.PaymentId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.PropertyId&lt;/class&gt;
            &lt;class&gt;ch.bemar.account.persistence.model.UserTypeId&lt;/class&gt;
  
            &lt;properties&gt;
                &lt;property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /&gt;
                &lt;property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jaccount_test" /&gt;
                &lt;property name="javax.persistence.jdbc.user" value="jaccount_test" /&gt;
                &lt;property name="javax.persistence.jdbc.password" value="testpw" /&gt;
  
                &lt;property name="hibernate.show_sql" value="true" /&gt;
  
                &lt;property name="hibernate.cache.provider_configuration_file_resource_path"
                    value="ehcache.xml" /&gt;
                &lt;property name="hibernate.cache.use_second_level_cache"
                    value="true" /&gt;
                &lt;property name="hibernate.cache.use_query_cache" value="false" /&gt;
                &lt;property name="hibernate.cache.region.factory_class"
                    value="org.hibernate.cache.ehcache.EhCacheRegionFactory" /&gt;
                &lt;property name="hibernate.cache.provider_class" value="org.hibernate.cache.ehcache.EhCacheProvider" /&gt;
                &lt;property name="hibernate.generate_statistics" value="true"/&gt;
            &lt;/properties&gt;
  
        &lt;/persistence-unit&gt;
      &lt;/persistence&gt;
  </code></pre>
  </blockquote>
  
  <p>Customer.java</p>
  
  <pre><code>@Entity
  @Cache(region = "customer", usage = CacheConcurrencyStrategy.READ_ONLY)
  @Table(name = "customer")
  public class Customer {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "custermer_id", unique = true, nullable = false)
      private Long customerId;
  
      @Column(name = "customer_name", nullable = false)
      private String customerName;
  
      @Column(name = "customer_descr")
      private String customerDescripton;
  
      @Column(name = "customer_selected", nullable = false)
      private Boolean selected;
  
      public Long getCustomerId() {
          return this.customerId;
      }
  
      public void setCustomerId(Long customerId) {
          this.customerId = customerId;
      }
  
      public String getCustomerName() {
          return this.customerName;
      }
  
      public void setCustomerName(String customerName) {
          this.customerName = customerName;
      }
  
      public String getCustomerDescripton() {
          return this.customerDescripton;
      }
  
      public void setCustomerDescripton(String customerDescripton) {
          this.customerDescripton = customerDescripton;
      }
  
      public Boolean getSelected() {
          return this.selected;
      }
  
      public void setSelected(Boolean selected) {
          this.selected = selected;
      }
  </code></pre>
  
  <p>Test</p>
  
  <pre><code>package ch.bemar.account.test.persistence;
  
  import java.util.Iterator;
  
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  
  import org.apache.commons.lang.StringUtils;
  import org.hibernate.Query;
  import org.hibernate.Session;
  import org.junit.Test;
  
  import ch.bemar.account.persistence.model.Customer;
  
  public class CacheTest2 {
  
      // private MyEntityManager persistenceEngine;
  
      @Test
      public void testRaw() {
          EntityManagerFactory factory = Persistence.createEntityManagerFactory("jaccount");
          EntityManager entityManager = factory.createEntityManager();
  
  
          Session session = (Session) entityManager.getDelegate();
  
          String hql = "from Customer";
          Query query = session.createQuery(hql);
          query.setCacheable(true);
  
          Iterator it = query.list().iterator();
          while (it.hasNext()) {
              Customer account = (Customer) it.next();
              System.out.println(account);
          }
  
          query = session.createQuery(hql);
          query.setCacheable(true);
  
          it = query.list().iterator();
          while (it.hasNext()) {
              Customer account = (Customer) it.next();
              System.out.println(account);
          }
  
          System.out.println(commaToCr(session.getSessionFactory().getStatistics()));
      }
  
      private String commaToCr(Object text) {
          return StringUtils.replace(text.toString(), ",", "\n");
      }
  }
  </code></pre>
  
  <p>Test Output</p>
  
  <pre><code> HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
      HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
      HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
      HHH000402: Using Hibernate built-in connection pool (not for production use!)
      Cache region factory : org.hibernate.cache.ehcache.EhCacheRegionFactory
      No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/C:/Users/bemar/.m2/repository/net/sf/ehcache/ehcache-core/2.4.3/ehcache-core-2.4.3.jar!/ehcache-failsafe.xml
      Configuring ehcache from URL: jar:file:/C:/Users/bemar/.m2/repository/net/sf/ehcache/ehcache-core/2.4.3/ehcache-core-2.4.3.jar!/ehcache-failsafe.xml
      Configuring ehcache from InputStream
      Ignoring ehcache attribute xmlns:xsi
      Ignoring ehcache attribute xsi:noNamespaceSchemaLocation
      Disk Store Path: C:\Users\bemar\AppData\Local\Temp\
      propertiesString is null.
      No CacheManagerEventListenerFactory class specified. Skipping...
      No BootstrapCacheLoaderFactory class specified. Skipping...
      CacheWriter factory not configured. Skipping...
      No CacheExceptionHandlerFactory class specified. Skipping...
      HHH020003: Could not find a specific ehcache configuration for cache named [year]; using defaults.
      Deleting data file year.data
      Initialised cache: year
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'year'.
      started EHCache region: year
      HHH020003: Could not find a specific ehcache configuration for cache named [language]; using defaults.
      Deleting data file language.data
      Initialised cache: language
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'language'.
      started EHCache region: language
      HHH020007: read-only cache configured for mutable entity [language]
      HHH020003: Could not find a specific ehcache configuration for cache named [type]; using defaults.
      Deleting data file type.data
      Initialised cache: type
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'type'.
      started EHCache region: type
      HHH020007: read-only cache configured for mutable entity [type]
      HHH020003: Could not find a specific ehcache configuration for cache named [i18n]; using defaults.
      Deleting data file i18n.data
      Initialised cache: i18n
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'i18n'.
      started EHCache region: i18n
      HHH020007: read-only cache configured for mutable entity [i18n]
      HHH020003: Could not find a specific ehcache configuration for cache named [property]; using defaults.
      Deleting data file property.data
      Initialised cache: property
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'property'.
      started EHCache region: property
      HHH020007: read-only cache configured for mutable entity [property]
      HHH020003: Could not find a specific ehcache configuration for cache named [account]; using defaults.
      Deleting data file account.data
      Initialised cache: account
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'account'.
      started EHCache region: account
      HHH020007: read-only cache configured for mutable entity [account]
      HHH020003: Could not find a specific ehcache configuration for cache named [user_type]; using defaults.
      Deleting data file user_type.data
      Initialised cache: user_type
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'user_type'.
      started EHCache region: user_type
      HHH020007: read-only cache configured for mutable entity [user_type]
      HHH020003: Could not find a specific ehcache configuration for cache named [i18n_group]; using defaults.
      Deleting data file i18n_group.data
      Initialised cache: i18n_group
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'i18n_group'.
      started EHCache region: i18n_group
      HHH020007: read-only cache configured for mutable entity [i18n_group]
      HHH020003: Could not find a specific ehcache configuration for cache named [category]; using defaults.
      Deleting data file category.data
      Initialised cache: category
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'category'.
      started EHCache region: category
      HHH020007: read-only cache configured for mutable entity [category]
      HHH020003: Could not find a specific ehcache configuration for cache named [i18n_item]; using defaults.
      Deleting data file i18n_item.data
      Initialised cache: i18n_item
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'i18n_item'.
      started EHCache region: i18n_item
      HHH020007: read-only cache configured for mutable entity [i18n_item]
      HHH020003: Could not find a specific ehcache configuration for cache named [customer]; using defaults.
      Deleting data file customer.data
      Initialised cache: customer
      CacheDecoratorFactory not configured for defaultCache. Skipping for 'customer'.
      started EHCache region: customer
      HHH020007: read-only cache configured for mutable entity [customer]
      Hibernate: select customer0_.custermer_id as custerme1_3_, customer0_.customer_descr as customer2_3_, customer0_.customer_name as customer3_3_, customer0_.customer_selected as customer4_3_ from customer customer0_
      ch.bemar.account.persistence.model.Customer@62b2a4
      ch.bemar.account.persistence.model.Customer@dbd080
      Hibernate: select customer0_.custermer_id as custerme1_3_, customer0_.customer_descr as customer2_3_, customer0_.customer_name as customer3_3_, customer0_.customer_selected as customer4_3_ from customer customer0_
      ch.bemar.account.persistence.model.Customer@62b2a4
      ch.bemar.account.persistence.model.Customer@dbd080
      Statistics[start time=1488717305688
      sessions opened=1
      sessions closed=0
      transactions=0
      successful transactions=0
      optimistic lock failures=0
      flushes=0
      connections obtained=1
      statements prepared=2
      statements closed=0
      second level cache puts=2
      second level cache hits=0
      second level cache misses=0
      entities loaded=2
      entities updated=0
      entities inserted=0
      entities deleted=0
      entities fetched=0
      collections loaded=0
      collections updated=0
      collections removed=0
      collections recreated=0
      collections fetched=0
      naturalId queries executed to database=0
      naturalId cache puts=0
      naturalId cache hits=0
      naturalId cache misses=0
      naturalId max query time=0
      queries executed to database=2
      query cache puts=0
      query cache hits=0
      query cache misses=0
      update timestamps cache puts=0
      update timestamps cache hits=0
      update timestamps cache misses=0
      max query time=35]
  </code></pre>
  
  <p>Thank you for your help</p>
  
  <p>Benjamin</p>