简体   繁体   English

java.lang.NullPointerException Hibernate与Ehc​​ache一起使用

[英]java.lang.NullPointerException Hibernate used with Ehcache

I used Hibernate 4.1.2 with Ehcache 2.4.3 (shipped together with hibernate when donwloaded hibernate). 我将Hibernate 4.1.2与Ehcache 2.4.3一起使用(在下载hibernate时与hibernate一起提供)。

My hibernate.cfg.xml : 我的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 : 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>   

mapping.xml mapping.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>

However, I got this exception : 但是,我得到了这个例外:

     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)
          ............

It seems that hibernate can not load configuration? 看来hibernate无法加载配置? How can I solve the problem? 我该如何解决这个问题? (The serlvet works fine without using Ehcache). (serlvet在没有使用Ehcache的情况下工作正常)。

My servlet class : 我的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();
       }    
}

} } 在此输入图像描述

Finally I found the reason why my code didn't work. 最后我找到了我的代码不起作用的原因。 Thanks for Vinodn for your suggestion. 感谢Vinodn的建议。

config.getDefaultCacheConfiguration().isTerracottaClustered() 

Actually, I didn't configure defaultCache tag in my ehcache-entity.xml, as a result 实际上,我没有在我的ehcache-entity.xml中配置defaultCache标签

config.getDefaultCacheConfiguration()

return null. 返回null。 So adding defaultCache solved the problem. 因此添加defaultCache解决了这个问题。

ehcache-entity.xml放在要由hibernate配置加载的类路径中。

That's allright. 没关系。 You do not have to explicitly specify value for property "net.sf.ehcache.configurationResourceName" if the resource is named ehcache.xml and placed in a class path. 如果资源名为ehcache.xml并放在类路径中,则不必为属性“net.sf.ehcache.configurationResourceName”显式指定值。 You can chose this option when you have multiple cache managers. 如果有多个缓存管理器,则可以选择此选项。

Or you can just move all your resource files from lib to a directory like WEB-INF/resources so that it becomes easier to reference it under classpath. 或者您可以将所有资源文件从lib移动到WEB-INF / resources之类的目录,以便在类路径下更容易引用它。

Ehcache looks for a file called ehcache.xml in the top level of the classpath. Ehcache在类路径的顶层查找名为ehcache.xml的文件。 Failing that it looks for ehcache-failsafe.xml in the classpath. 如果没有在类路径中查找ehcache-failsafe.xml。 ehcache-failsafe.xml is packaged in the Ehcache jar and should always be found. ehcache-failsafe.xml包装在Ehcache jar中,应该始终可以找到。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM