我几乎阅读了有关如何配置hibernate数据源的所有帖子,但我找不到帮助。我的意思是hibernate.cfg.xml
元素<property name="hibernate.connection.datasource"> ? </property>
我知道我必须设置jndi。我尝试谷歌它,但所有文章都基于jbossas,ejb,tomcat,weblogic和他们的jndi开发。但我需要java SE的jndi。如果我错了,请纠正我。
我是Hibernate的新手,所以我使用的是带有Hibernate 3.2.5 jar的NetBeans,SE项目。 (我正在从书籍Beginning Hibernate第二版开始学习Hibernate,这本书上的apress和源代码......)
我的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]
答案 0 :(得分:0)
您不需要SE的复杂设置。 希望这个链接有帮助
答案 1 :(得分:0)
从我认为你在非托管环境中配置hibernate。在非托管环境中,hibernate通过简单的连接池处理连接。不可能在非托管模式下配置数据源。您可以查看http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/transactions.html#transactions-demarcation-nonmanaged了解更多详情。