java.lang.NullPointerException Hibernate used with Ehcache

穿精又带淫゛_ 提交于 2020-01-02 07:23:22

问题


I used Hibernate 4.1.2 with Ehcache 2.4.3 (shipped together with hibernate when donwloaded hibernate).

My 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>   

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? How can I solve the problem? (The serlvet works fine without using Ehcache).

My servlet class :

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

}


回答1:


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

Ehcache looks for a file called ehcache.xml in the top level of the classpath. Failing that it looks for ehcache-failsafe.xml in the classpath. ehcache-failsafe.xml is packaged in the Ehcache jar and should always be found.




回答2:


Finally I found the reason why my code didn't work. Thanks for Vinodn for your suggestion.

config.getDefaultCacheConfiguration().isTerracottaClustered() 

Actually, I didn't configure defaultCache tag in my ehcache-entity.xml, as a result

config.getDefaultCacheConfiguration()

return null. So adding defaultCache solved the problem.




回答3:


Place ehcache-entity.xml in your classpath to be loaded by your hibernate configuration.




回答4:


adding defaultCache configuration in ehcache.xml help me too.



来源:https://stackoverflow.com/questions/10266359/java-lang-nullpointerexception-hibernate-used-with-ehcache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!