有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate SessionFactory:如何在Tomcat中配置JNDI?

这就是会话工厂的获取方式:

    protected SessionFactory getSessionFactory() {
        try {
            return (SessionFactory) new InitialContext()
                    .lookup("SessionFactory");
        } catch (Exception e) {
        }
    }

请为Tomcat6提供一个能够获取SessionFactory的简单解决方案 通过Java代码中的简单jndi查找。 Tomcat应该在哪个文件中写入什么?


共 (2) 个答案

  1. # 1 楼答案

    Tomcat文档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.

    Hibernate文档说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 use hibernate.session_factory_name property, because Tomcat provide read-only JNDI implementation. To use JNDI-bound SessionFactory with Tomcat, you should write custom resource factory class for SessionFactory and setup it Tomcat's configuration.

    因此,您需要将自定义SessionFactory设置为:

    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;  
       }  
    }