[转载]Hibernate出现javax.naming.NoInitialContextException 错误的解决办法

2014-02-09 16:44

原文地址: http://hi.baidu.com/cliff77/blog/item/16aad2fb354a44106c22eb1b.html

使用学习Hibernate时,突然出现了以下的错误:

Could not bind factory to JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
        at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
        at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
        at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
        at javax.naming.InitialContext.getNameParser(InitialContext.java:480)
        at org.hibernate.util.NamingHelper.bind(NamingHelper.java:52)
        at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(SessionFactoryObjectFactory.java:90)
        at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:306)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
        at ch01.HibernateTest.main(HibernateTest.java:32)

看内容应该是JNDI没有初始化造成的。我的程序很简单,没有用到JNDI啊?百思不得其解,终于发现在Netbeans自动生成的Hibernate配置文件有一点问题:

<hibernate-configuration>
<session-factory name="session1">
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">123</property>
    <mapping resource="Login.hbm.xml"/>
</session-factory>
</hibernate-configuration>

我平时自己写配置文件,都是写

<session-factory>

     ……

</session-factory>

而这里恰恰多了一个name属性,这样,hibernate会试图把这个sessionfacotry注册到jndi中去,这样就出现了这样的错误。唉,浪费了N小时。