【问题标题】:Hibernate Ehcache not using cached dataHibernate Ehcache 不使用缓存数据
【发布时间】:2017-03-05 13:13:43
【问题描述】:

我正在尝试让 ehcache 在非 Spring 环境中工作(带有 Hibernate Entity Manager 的 Swing 客户端)。

缓存似乎可以工作,但出于某种原因,缓存将所有查询发送到数据库,而不是使用缓存的值。

但我不知道为什么。

我们将不胜感激。

这是我的环境:

 <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate.common</groupId>
      <artifactId>hibernate-commons-annotations</artifactId>
      <version>4.0.4.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.11.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.5.6-Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.11.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>4.3.11.Final</version>
      <scope>compile</scope>
    </dependency>

ehcache.xml

 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
            monitoring="autodetect" dynamicConfig="true">

         <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="120"
                overflowToDisk="false"
                diskSpoolBufferSizeMB="30"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120"
                memoryStoreEvictionPolicy="LRU"
                />
    </ehcache>

persistence.xml

 <?xml version="1.0" encoding="UTF-8" ?>
    <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">

      <persistence-unit name="jaccount" transaction-type="RESOURCE_LOCAL">
          <class>ch.bemar.account.persistence.model.Account</class>
          <class>ch.bemar.account.persistence.model.AccountId</class>
          <class>ch.bemar.account.persistence.model.Booking</class>
          <class>ch.bemar.account.persistence.model.BookingId</class>
          <class>ch.bemar.account.persistence.model.Category</class>
          <class>ch.bemar.account.persistence.model.CategoryId</class>
          <class>ch.bemar.account.persistence.model.Property</class>
          <class>ch.bemar.account.persistence.model.Type</class>
          <class>ch.bemar.account.persistence.model.Year</class>
          <class>ch.bemar.account.persistence.model.YearId</class>
          <class>ch.bemar.account.persistence.model.I18n</class>
          <class>ch.bemar.account.persistence.model.I18nGroup</class>
          <class>ch.bemar.account.persistence.model.I18nItem</class>
          <class>ch.bemar.account.persistence.model.Language</class>
          <class>ch.bemar.account.persistence.model.User</class>
          <class>ch.bemar.account.persistence.model.UserId</class>
          <class>ch.bemar.account.persistence.model.Payment</class>
          <class>ch.bemar.account.persistence.model.UserType</class>
          <class>ch.bemar.account.persistence.model.Customer</class>
          <class>ch.bemar.account.persistence.model.PaymentId</class>
          <class>ch.bemar.account.persistence.model.PropertyId</class>
          <class>ch.bemar.account.persistence.model.UserTypeId</class>

          <properties>
              <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
              <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jaccount_test" />
              <property name="javax.persistence.jdbc.user" value="jaccount_test" />
              <property name="javax.persistence.jdbc.password" value="testpw" />

              <property name="hibernate.show_sql" value="true" />

              <property name="hibernate.cache.provider_configuration_file_resource_path"
                  value="ehcache.xml" />
              <property name="hibernate.cache.use_second_level_cache"
                  value="true" />
              <property name="hibernate.cache.use_query_cache" value="false" />
              <property name="hibernate.cache.region.factory_class"
                  value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />
              <property name="hibernate.cache.provider_class" value="org.hibernate.cache.ehcache.EhCacheProvider" />
              <property name="hibernate.generate_statistics" value="true"/>
          </properties>

      </persistence-unit>
    </persistence>

客户.java

@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;
    }

测试

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");
    }
}

测试输出

 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]

感谢您的帮助

本杰明

【问题讨论】:

  • &lt;property name="hibernate.cache.use_query_cache" value="false" /&gt; 这是你的persistence.xml,所以它被禁用了,或者我错过了什么。
  • 缓存不会“将所有查询发送到数据库”;缓存是否有对象会回复。持久性提供程序是唯一向数据库发送查询的东西

标签: hibernate jpa ehcache


【解决方案1】:

好的。那是相当尴尬的。在我打开查询缓存之后

<property name="hibernate.cache.use_query_cache" value="true" />

成功了。

谢谢大家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-20
    • 2012-12-12
    • 1970-01-01
    • 2014-03-03
    • 2015-04-24
    • 2013-11-23
    • 2017-03-06
    • 2014-11-10
    相关资源
    最近更新 更多