问题描述
||
我只是在尝试将Hibernate实现为Glassfish应用程序服务器中的持久性提供程序。我已经配置了JNDI数据源,连接池等。我的Hibernate配置如下:
<?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>
<session-factory>
<property name=\"hibernate.connection.datasource\">jdbc/myDatasource</property>
<property name=\"hibernate.dialect\">org.hibernate.dialect.MysqLDialect</property>
<property name=\"hibernate.connection.factory_class\">net.sf.hibernate.transaction.JTATransactionFactory</property>
<property name=\"hibernate.session_factory_name\">hibernateSessionFactory</property>
<property name=\"hibernate.show_sql\">true</property>
<property name=\"hibernate.hbm2ddl.auto\">validate</property>
<property name=\"hibernate.current_session_context_class\">thread</property>
<mapping class=\"org.me.jsf.entities.Node\" />
</session-factory>
</hibernate-configuration>
当我尝试以这种方式使用Session Factory时:
try {
sessionFactory = (SessionFactory) new InitialContext()
.lookup(\"hibernateSessionFactory\");
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
我收到一个异常“ ExceptionInInitializerError \”,该异常是根据日志“ \'hibernateSessionFactory \'\的查找失败”引起的。但是当我使用此代码时:
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
...一切都很好。
我在这里错了吗?我什至尝试在faces-config.xml中为相关类的托管bean hibernateSessionFactory输入一个条目,但还是没有运气...
解决方法
ѭ3的存在意味着会话工厂在创建时将绑定到JNDI,但是您仍然要执行在启动期间创建它的代码。从Hibernate文档中:
调用cfg.buildSessionFactory()之后,Hibernate将自动将SessionFactory放入JNDI中。这意味着您将在某些启动代码或应用程序中的实用程序类中进行此调用,除非您将JMX部署与HibernateService一起使用(稍后将对此进行详细讨论)。