I’m just playing around with implementing Hibernate as persistence provider in Glassfish application server. I already configured JNDI datasource, connection pool etc. My Hibernate config is as follows:
<?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>
When I try to use Session Factory this way:
try {
sessionFactory = (SessionFactory) new InitialContext()
.lookup("hibernateSessionFactory");
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
I get an exception “ExceptionInInitializerError”, caused by, according to the logs, “Lookup failed for ‘hibernateSessionFactory'”. But when I use this code:
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
…everything goes fine.
What I got wrong here? I even tried to make an entry for managed bean hibernateSessionFactory for relevant class in faces-config.xml, but still no luck…
Presence of
hibernate.session_factory_namemeans that session factory will be bound to JNDI when created, but you still to execute a code that creates it during startup. From Hibernate documentation: