1

我正在使用 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: Name SessionFactory is not bound in this Context at org.apache.naming.NamingContext.lookup(NamingContext.java:803) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org .apache.naming.SelectorContext.lookup(SelectorContext.java:158) at javax.naming.InitialContext.lookup(Unknown Source) at com.webapplication.service.AuthorHome.getSessionFactory(AuthorHome.java:31) at com.webapplication.service .AuthorHome.(AuthorHome.java:26)

4

1 回答 1

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

于 2012-03-18T13:24:44.307 回答