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

时间:2010-03-19 08:44:01

标签: java hibernate tomcat jndi sessionfactory

应该如何获得会话工厂:

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

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

2 个答案:

答案 0 :(得分:2)

这是一个链接 http://community.jboss.org/wiki/UsingJNDI-boundSessionFactorywithTomcat41

但也欢迎其他答案。

答案 1 :(得分:0)

Tomcat文档WebIDE Screenshot

  

Tomcat提供只读hibernate.session_factory_name,而Hibernate需要   读写以管理多个会话工厂。 Tomcat是   显然遵循非托管容器的规范。如果   您希望将会话工厂绑定到JNDI对象,您也可以   必须移动到托管服务器(Glassfish,JBoss等),或搜索   在互联网上进行一些公布的解决方案。

     

Hibernate文档的建议就是离开   在使用时输出hibernate.session_factory_name属性   Tomcat不尝试绑定到JNDI。

Hibernate文档说says

  

将SessionFactory绑定到JDNI名称空间非常有用。在   在大多数情况下,可以使用hibernate.session_factory_name   您配置中的属性。但是,使用Tomcat你无法使用   SessionFactory属性,因为Tomcat提供   只读JNDI实现。使用JNDI绑定的SessionFactory   Tomcat,您应该为自定义资源工厂类编写   SessionFactory并设置Tomcat的配置。

所以你需要像这样制作自定义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; } }

// Session config goes here...
session_save_path("/tmp");
if (session_status() != PHP_SESSION_DISABLED) {
    session_start();
} else {
    die("Sessions are disabled. Sorry");
 }
 //Session is alive and well here could double check using if (session_status() == PHP_SESSION_ACTIVE)