java.lang.NullPointerException Hibernate与Ehc​​ache一起使用 [英] java.lang.NullPointerException Hibernate used with Ehcache

查看:91
本文介绍了java.lang.NullPointerException Hibernate与Ehc​​ache一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了Hibernate 4.1.2和Ehcache 2.4.3(当hibernate被donwloaded时,与hibernate一起发布)。

我的hibernate.cfg.xml:

 <?xml version ='1.0'encoding ='utf-8'?> 
<!DOCTYPE hibernate-configuration PUBLIC
- // Hibernate / Hibernate配置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://本地主机:1433;的databaseName = Stock_indices< /性>
< 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>更新< / 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_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.0encoding =UTF-8?> 
< ehcache>

< cache name =stockdata.StockDatabaseConnectioneternal =false
maxElementsInMemory =5overflowToDisk =truediskPersistent =false
timeToIdleSeconds =0 timeToLiveSeconds =300
memoryStoreEvictionPolicy =LRU/>

< / ehcache>

mapping.xml

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

< hibernate-mapping package =stockdata>

< class name =StockDatabaseConnectiontable =STOCKINDEX>

< cache usage =read-only/>
< composite-id name =CompositeIDConnection>
< key-property name =tickercolumn =TICKER/>
< key-property name =indexdatecolumn =INDEXDATE/>
< / composite-id>

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


< / class>
< / hibernate-mapping>

然而,我得到这个例外:

  java.lang.NullPointerException在org.hibernate.cache.ehcache.internal.util.HibernateUtil.loadAndCorrectConfiguration(HibernateUtil.java:64)
在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)
............

看来,休眠不能加载配置?我该如何解决这个问题? (serlvet在没有使用Ehcache的情况下工作正常)。



我的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;
导入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扩展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();



保护无效doGet(HttpServletRequest请求,HttpServletResponse响应){
Session session = null;
尝试{
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();
}
}

}

解决方案

这就是好吧。
如果资源名为ehcache.xml并放置在类路径中,则不必为属性net.sf.ehcache.configurationResourceName显式指定值。如果您有多个缓存管理器,则可以选择此选项。



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


Ehcache在类路径的顶层查找名为ehcache.xml的文件。如果它没有在类路径中查找ehcache-failsafe.xml。 ehcache-failsafe.xml打包在Ehcache jar中,应该始终找到。



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

}

解决方案

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.

这篇关于java.lang.NullPointerException Hibernate与Ehc​​ache一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆