gpt4 book ai didi

javax.naming.NameNotFoundException : Name [SessionFactory] is not bound in this Context. 无法找到 [SessionFactory]

转载 作者:行者123 更新时间:2023-11-29 05:26:43 26 4
gpt4 key购买 nike

我正在尝试在我的 Spring 应用程序中使用 Hibernate 进行 Db 访问。但是现在,我收到以下错误:

Could not locate SessionFactory in JNDI
javax.naming.NameNotFoundException: Name [SessionFactory] is not bound in this Context. Unable to find [SessionFactory].
at org.apache.naming.NamingContext.lookup(NamingContext.java:820)
at org.apache.naming.NamingContext.lookup(NamingContext.java:168)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at org.ligadesportiva.data.UsuarioHome.getSessionFactory(UsuarioHome.java:28)
at org.ligadesportiva.data.UsuarioHome.<init>(UsuarioHome.java:23)
at org.ligadesportiva.controller.controller.login(controller.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

这是我的类 DAO (UsuarioHome.java):

package org.ligadesportiva.data;

// Generated 15/03/2014 09:34:19 by Hibernate Tools 3.4.0.CR1

import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.ligadesportiva.core.Usuario;

/**
* Home object for domain model class Usuario.
* @see org.ligadesportiva.core.Usuario
* @author Hibernate Tools
*/
public class UsuarioHome {

private static final Log log = LogFactory.getLog(UsuarioHome.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");
}
}

public void persist(Usuario transientInstance) {
log.debug("persisting Usuario instance");
try {
sessionFactory.getCurrentSession().persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}

public void attachDirty(Usuario instance) {
log.debug("attaching dirty Usuario instance");
try {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void attachClean(Usuario instance) {
log.debug("attaching clean Usuario instance");
try {
sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void delete(Usuario persistentInstance) {
log.debug("deleting Usuario instance");
try {
sessionFactory.getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}

public Usuario merge(Usuario detachedInstance) {
log.debug("merging Usuario instance");
try {
Usuario result = (Usuario) sessionFactory.getCurrentSession()
.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public Usuario findById(int id) {
log.debug("getting Usuario instance with id: " + id);
try {
Usuario instance = (Usuario) sessionFactory.getCurrentSession()
.get("org.ligadesportiva.data.Usuario", id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}

public List findByExample(Usuario instance) {
log.debug("finding Usuario instance by example");
try {
List results = sessionFactory.getCurrentSession()
.createCriteria("org.ligadesportiva.data.Usuario")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
}

这个方法是从我的 Controller 调用的,这样:

@RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();

Usuario temp = new Usuario(username, convertByteToHex(digest));
UsuarioHome tempHome = new UsuarioHome();
List<Usuario> lista = tempHome.findByExample(temp);
if(lista.size() == 0) {
ModelAndView mav = new ModelAndView();
mav.setViewName("usuario_login");
mav.addObject("message", "N&atilde;o foi possivel efetuar o login");
return mav;
}
else {
this.sessao = new Sessao();
ModelAndView mav = new ModelAndView();
mav.setViewName("usuario_start");
mav.addObject("usuario", temp);
return mav;
}
}

有人可以识别我做错了什么吗?

更新 1根据 CodeBlender 的建议,我将这个类添加到我的项目中(在包 org.ligadesportiva.resources 中):

package org.ligadesportiva.resources;

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database.properties" })
@ComponentScan({ "org.ligadesportiva.data" })
public class HibernateConfig {

@Autowired
private Environment env;

@Bean
public AnnotationSessionFactoryBean sessionFactory() {
AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "org.ligadesportiva.core" });
sessionFactory.setHibernateProperties(hibernateProperties());

return sessionFactory;
}

@Bean
public DataSource restDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));

return dataSource;
}

@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());

return txManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}

Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
}
};
}
}

并将此行添加到我的类 UsuarioHome(DAO 类):

private HibernateConfig hibernateConfig = new HibernateConfig();

private final SessionFactory sessionFactory = (SessionFactory) hibernateConfig.sessionFactory();

我不知道我做的对不对,但是报错信息变成了这样:

最佳答案

您的错误是由 (SessionFactory) new InitialContext().lookup("SessionFactory") 引起的。由于您使用的是 spring 框架,我建议您使用 IoC 方法而不是使用 InitialContext。 =)

要使用 SessionFactory,您需要使用多个属性初始化此类,例如数据源、hibernateProperties、实体等。通常使用 XML 或注释驱动方法完成。您将配置 SessionFactory 并让它存在于您的 IoC 容器中,然后将其注入(inject)您的 UsuarioHome 类。

http://www.javacodegeeks.com/2013/05/hibernate-3-with-spring.html

上面的链接显示了两种方法(XML 和注释)。尝试遵循它并设置 bean。 =D

更新:这个 mkyong 的教程包含分步教程,而且非常清晰! http://www.mkyong.com/spring/maven-spring-hibernate-mysql-example/

关于javax.naming.NameNotFoundException : Name [SessionFactory] is not bound in this Context. 无法找到 [SessionFactory],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424471/

26 4 0