2012-02-15 32 views
0

我几乎读过所有关于如何配置hibernate数据源的主题,但找不到帮助。我的意思是在hibernate.cfg.xml元素<property name="hibernate.connection.datasource"> ? </property>我知道我必须设置jndi。我试图谷歌它,但所有文章都基于与jbossas,ejb,tomcat,weblogic和他们的jndi开发。但是我需要java SE的jndi。请纠正我,如果我错了。如何在Java中设置休眠数据源SE

我是Hibernate的新手,所以我使用的是带有Hibernate 3.2.5 jar的NetBeans SE项目。 (我从书中学习Hibernate的开始Hibernate的第二版,A按和源代码在本书中获得...)

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
    <hibernate-configuration> 
    <property name="hibernate.connection.driver_class"> 
     com.mysql.jdbc.Driver 
    </property> 
    <property name="hibernate.connection.url"> 
     jdbc:mysql://127.0.0.1:3306/asd 
    </property> 
    <property name="hibernate.connection.username">root</property> 

    <!-- nastaveni dialektu --> 
    <property name="hibernate.dialect"> 
     org.hibernate.dialect.MySQLInnoDBDialect 
    </property> 

    <!-- jndi nastaveni --> 
    <property name="hibernate.connection.datasource"> 
     java:hibernate/SessionFactory 
    </property> 
    <property name="hibernate.connection.username">root</property> 
    <property name="cache.provider_class"> 
     org.hibernate.cache.NoCacheProvider 
    </property> 
    <property name="hibernate.jndi.class">javax.naming.InitialContext</property> 
    </session-factory> 
</hibernate-configuration> 

而且我只有一个FirstHibernate类:

package firsthibernate; 

import java.util.List; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.AnnotationConfiguration; 

public class FirstHibernate { 

    private static SessionFactory session = null; 
    private static Session s = null; 

    public static void main(String[] args) { 
     try { 
      session = new AnnotationConfiguration().configure().buildSessionFactory(); 
      s = session.openSession(); 

      s.beginTransaction(); 
      // List l = s.createQuery("from query").list(); 
      s.getTransaction().commit(); 
     } catch (Exception ex) { 
      if (s.getTransaction() != null) { 
       //s.getTransaction().rollback(); 
      } 
      System.out.println(ex.toString()); 
     } finally { 
      s.close(); 
     } 
    } 
} 

我收到此消息:

SEVERE: Could not obtain initial context javax.naming.NoInitialContextException: Cannot instantiate class: javax.naming.InitialContext [Root exception is java.lang.ClassCastException: javax.naming.InitialContext cannot be cast to javax.naming.spi.InitialContextFactory] 

回答