Hibernate SessionFactory: how to configure JNDI in Tomcat?
that's how the session factory should be gotten:
protected SessionFactory getSessionFactory() { try { return (SessionFactory) new InitialContext() 开发者_JAVA技巧 .lookup("SessionFactory"); } catch (Exception e) { } }
Please provide a simple solution for Tomcat6 to be able to get SessionFactory thru simple jndi lookup in Java code. What should be written in what file on the side of Tomcat ?
Here's a link http://community.jboss.org/wiki/UsingJNDI-boundSessionFactorywithTomcat41
But other answers are welcome as well.
Tomcat documentation says:
Tomcat provides a read-only
InitialContext
, while Hibernate requires read-write in order to manage multiple session factories. Tomcat is apparently following the specification for unmanaged containers. If you want to bind the session factory to a JNDI object, you'll either have to move to a managed server (Glassfish, JBoss, etc.), or search on the Internet for some posted work-arounds.The recommendation from the Hibernate documentation is to just leave out the
hibernate.session_factory_name
property when working with Tomcat to not try binding to JNDI.
And Hibernate documentation says the same:
It is very useful to bind your SessionFactory to JDNI namespace. In most cases, this is possible to use
hibernate.session_factory_name
property in your configuration. But, with Tomcat you cann't usehibernate.session_factory_name
property, because Tomcat provide read-only JNDI implementation. To use JNDI-boundSessionFactory
with Tomcat, you should write custom resource factory class forSessionFactory
and setup it Tomcat's configuration.
So you need to make custom SessionFactory
like that:
package myutil.hibernate;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.Name;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.RefAddr;
import javax.naming.spi.ObjectFactory
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactoryTomcatFactory implements ObjectFactory{
public Object getObjectInstance(Object obj, Name name, Context cntx, Hashtable env)
throws NamingException{
SessionFactory sessionFactory = null;
RefAddr addr = null;
try{
Enumeration addrs = ((Reference)(obj)).getAll();
while(addrs.hasMoreElements()){
addr = (RefAddr) addrs.nextElement();
if("configuration".equals((String)(addr.getType()))){
sessionFactory = (new Configuration())
.configure((String)addr.getContent()).buildSessionFactory();
}
}
}catch(Exception ex){
throw new javax.naming.NamingException(ex.getMessage());
}
return sessionFactory;
}
}
精彩评论