1

我只是在尝试将 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>

当我尝试以这种方式使用会话工厂时:

    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 条目,但仍然没有运气......

4

1 回答 1

1

的存在hibernate.session_factory_name意味着会话工厂在创建时将绑定到 JNDI,但您仍需执行在启动期间创建它的代码。从休眠文档

在调用 cfg.buildSessionFactory() 之后,Hibernate 会自动将 SessionFactory 放入 JNDI。这意味着您将在一些启动代码或应用程序中的实用程序类中调用此调用,除非您将 JMX 部署与 HibernateService 一起使用(稍后将更详细地讨论)。

于 2011-05-24T12:18:34.673 回答