Tomcat和Hibernate的JNDI会话工厂错误

时间:2012-03-18 13:11:22

标签: hibernate spring-mvc jndi tomcat7 hibernate-tools

我正在使用Spring MVC,Hibernate,JBoss Tools和JSF构建Web应用程序框架。我已经设法通过使用JBoss工具生成域类和DAO类,但是,当我尝试构造任何DAO对象时(目前我正在构建服务但最终服务将被注入控制器),我收到JNDI错误。我使用Tomcat 7作为AS。我很感激这个问题的简单解决方案。

控制器代码:

AuthorHome ah = new AuthorHome();
Author a = ah.findById(1);

DAO /服务代码:

public class AuthorHome {

private static final Log log = LogFactory.getLog(AuthorHome.class);

private final SessionFactory sessionFactory = getSessionFactory();

protected SessionFactory getSessionFactory() {
    try {
        return (SessionFactory) new InitialContext().lookup("SessionFactory");
    } catch (Exception e) {
        log.error("Could not locate SessionFactory in JNDI", e);
        throw new IllegalStateException(
                "Could not locate SessionFactory in JNDI");
    }
}
}

堆栈追踪:

  

javax.naming.NameNotFoundException:名称SessionFactory未绑定在此Context中       在org.apache.naming.NamingContext.lookup(NamingContext.java:803)       在org.apache.naming.NamingContext.lookup(NamingContext.java:159)       在org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)       在javax.naming.InitialContext.lookup(未知来源)       在com.webapplication.service.AuthorHome.getSessionFactory(AuthorHome.java:31)       在com.webapplication.service.AuthorHome。(AuthorHome.java:26)

1 个答案:

答案 0 :(得分:2)

您需要在Spring中配置Hibernate Session Factory。见http://static.springsource.org/spring/docs/current/spring-framework-reference/html/orm.html#orm-session-factory-setup。另请注意,在Spring内部直接使用Hibernate需要事务上下文。一种简单的方法是使用@Transactional注释。详情请见http://static.springsource.org/spring/docs/current/spring-framework-reference/html/transaction.html#transaction-declarative-annotations