3

我将 Hibernate 4.1.2 与 Ehcache 2.4.3 一起使用(下载 hibernate 时与 hibernate 一起提供)。

我的 hibernate.cfg.xml :

 <?xml version='1.0' encoding='utf-8'?>
  <!DOCTYPE hibernate-configuration PUBLIC
   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>
    <session-factory>
          <property name="hibernate.connection.driver_class">  com.microsoft.sqlserver.jdbc.SQLServerDriver </property>
          <property name="hibernate.connection.url"> jdbc:sqlserver://localhost:1433;databaseName=Stock_indices</property>
          <property name="hibernate.connection.username">xxx</property>
          <property name="hibernate.connection.password">xxx</property>
          <property name="hibernate.show_sql">true</property>
          <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
          <property name="hibernate.hbm2ddl.auto">update</property>
          <property name="hibernate.c3p0.min_size">5</property>
          <property name="hibernate.c3p0.max_size">20</property>
          <property name="hibernate.c3p0.timeout">300</property>
          <property name="hibernate.c3p0.max_statements">50</property>
          <property name="hibernate.c3p0.idle_test_period">30</property> 


          <property name="hibernate.cache.use_second_level_cache">true</property>
          <property name="hibernate.cache.use_query_cache">true</property>
          <property  name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory              </property>
          <property name="net.sf.ehcache.configurationResourceName">ehcache-entity.xml</property>

          <mapping resource="mapping.xml"/>

      </session-factory>
</hibernate-configuration>

ehcache-entity.xml:

<?xml version="1.0" encoding="UTF-8"?>
   <ehcache>

       <cache name="stockdata.StockDatabaseConnection" eternal="false"
        maxElementsInMemory="5" overflowToDisk="true" diskPersistent="false"
        timeToIdleSeconds="0" timeToLiveSeconds="300"
        memoryStoreEvictionPolicy="LRU" />

   </ehcache>   

映射.xml

   <?xml version="1.0"?>
  <!DOCTYPE hibernate-mapping PUBLIC
       "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">    

       <hibernate-mapping package="stockdata">

            <class name="StockDatabaseConnection" table="STOCKINDEX"> 

               <cache usage="read-only" />
                  <composite-id name="CompositeIDConnection">
            <key-property name="ticker" column="TICKER"/>
            <key-property name="indexdate" column="INDEXDATE"/>
          </composite-id>

                  <property name="openprice"> <column name="OPENPRICE" /> </property>
                  <property name="closingprice"> <column name="CLOSEPRICE" /> </property>
                  <property name="highestprice"> <column name="HIGHPRICE" /> </property>
                  <property name="lowestprice"> <column name="LOWPRICE" /> </property>
                  <property name="volume"> <column name="VOLUME" /> </property>


            </class>
     </hibernate-mapping>

但是,我得到了这个例外:

     java.lang.NullPointerException at   org.hibernate.cache.ehcache.internal.util.HibernateUtil.loadAndCorrectConfiguration(HibernateUtil.java:64)
  at  org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory.start(SingletonEhCacheRegionFactory.java:91)
 at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:281)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1741)
          ............

好像hibernate不能加载配置?我该如何解决这个问题?(不使用 Ehcache 的 serlvet 工作正常)。

我的 servlet 类:

package stockdataservlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.google.gson.Gson;
import com.microsoft.sqlserver.jdbc.*;


 public class DataServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;

     public static SessionFactory sessionfactory = null;
     public void init() {
         try {
             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
             Configuration conf = new Configuration();
             conf.configure();
             ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();   
             sessionfactory = conf.buildSessionFactory(serviceRegistry);

               }
       catch(Exception e){

        e.printStackTrace();
               }
               }

     protected void doGet(HttpServletRequest request, HttpServletResponse response) {
          Session session = null;
       try{
           session = sessionfactory.openSession();
           Transaction transaction = session.beginTransaction();
           Query query = session.createSQLQuery("SELECT * FROM STOCKINDEX WHERE TICKER = :index ").addScalar("CLOSEPRICE");
           query.setParameter("index", "AAA");
           List list = query.list();
           transaction.commit();
           String json = new Gson().toJson(list);
           /*response.setContentType("application/json");
           response.setCharacterEncoding("UTF-8");
           response.getWriter().write(json);*/
         }
       catch(Exception e){
        e.printStackTrace();

       }
         finally{

        session.close();
       }    
}

} 在此处输入图像描述

4

4 回答 4

3

最后我找到了我的代码不起作用的原因。感谢 Vinodn 的建议。

config.getDefaultCacheConfiguration().isTerracottaClustered() 

实际上,我没有在我的 ehcache-entity.xml 中配置defaultCache标签,结果

config.getDefaultCacheConfiguration()

返回空值。所以添加defaultCache解决了这个问题。

于 2012-04-24T12:43:01.343 回答
2

放置ehcache-entity.xml在您的类路径中以由您的休眠配置加载。

于 2012-04-24T21:10:29.457 回答
1

没关系。如果资源名为 ehcache.xml 并放置在类路径中,则不必显式指定属性“net.sf.ehcache.configurationResourceName”的值。当您有多个缓存管理器时,您可以选择此选项。

或者,您可以将所有资源文件从 lib 移动到 WEB-INF/resources 等目录,以便在类路径下更容易引用它。

Ehcache 在类路径的顶层查找名为 ehcache.xml 的文件。未能在类路径中查找 ehcache-failsafe.xml。ehcache-failsafe.xml 打包在 Ehcache jar 中,应该始终可以找到。

于 2012-04-25T13:39:22.670 回答
1

在 ehcache.xml 中添加 defaultCache 配置也对我有帮助。

于 2013-04-06T12:38:54.113 回答