当前位置: 首页 > 面试题库 >

在Spring / Hibernate项目中需要访问数据库时发生异常java.lang.NullPointerException

孙翰墨
2023-03-14
问题内容

我正在尝试在Spring应用程序中使用Hibernate进行Db访问。在依赖项出现一些问题(现已解决)之后,我可以正常运行我的项目,并且它的第一页对我打开(这是一个登录页面)。但是,当我将表单提交给服务器时(此请购单由spring控制器处理),我收到以下错误消息:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause

java.lang.NullPointerException
    org.ligadesportiva.resources.HibernateConfig.restDataSource(HibernateConfig.java:38)
    org.ligadesportiva.resources.HibernateConfig.sessionFactory(HibernateConfig.java:28)
    org.ligadesportiva.data.UsuarioHome.<init>(UsuarioHome.java:31)
    org.ligadesportiva.controller.controller.login(controller.java:36)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

这是控制器处理请求的方法:

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

这是我的类HibernateConfig:

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

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

这是我的类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 HibernateConfig hibernateConfig = new HibernateConfig();

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

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

这是我的*
-servlet.xml文件,在这里声明HibernateConfig,遵循此处的指示:http :
//docs.spring.io/spring/docs/3.1.x/javadoc-
api/org/springframework/context/注解/Configuration.html。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="org.ligadesportiva.controller" />
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <context:annotation-config/>
    <bean class="org.ligadesportiva.resources.HibernateConfig"/>
</beans>

有人可以看到此代码有什么问题吗?


问题答案:

Spring IoC容器的基本规则是让Spring管理大部分(如果不是全部)您的依赖项和对象。

您的HibernateConfig班级带有注释@Configuration。这表明它应该 由Spring管理
,您可以在上下文文件中正确地进行操作

<bean class="org.ligadesportiva.resources.HibernateConfig"/>

但是,您没有在任何地方使用它。您也没有声明UsuarioHomebean。相反,您自己创建这些对象

UsuarioHome tempHome = new UsuarioHome();
// and
private HibernateConfig hibernateConfig = new HibernateConfig();

您希望Spring如何处理它们?

浏览Spring IoC容器的文档,以了解如何通过上下文配置来管理这些依赖项。



 类似资料:
  • 我试图在OSGi(Felix)中使用新的Leap运动传感器,但我最终遇到了一个异常访问冲突。 在我的清单中,我声明捆绑NativeCode如 当然: 在OSGi之外使用相同库的简单程序运行良好 这两个库在“x86”文件夹中的我的包中 “osname=win32;processor=x86”适合我(已经用其他bunble进行了测试) 在反编译Leap Motion jar后,我看到LeapJava.

  • 问题内容: 我有以下代码: userDAO1.save(userRecord)违反了完整性约束-因此,在运行了整个代码之后,没有任何内容写入到userDAO1所引用的表中。 但是,userDAO1.save()语句不会引发错误/异常-因此,也会执行userDAO2.save()。 但是捕获了DataIntegrityViolationException,并且 堆栈跟踪为null 。 如何检查从何处

  • HTTP状态500-请求处理失败;嵌套异常为org.springframework.transaction.CanNotCreateTransactionException:无法打开事务的Hibernate会话;嵌套异常为Org.Hibernate.exception.GenericJDBCException:无法打开连接

  • Im使用spring 3.0.7、JUnit 4.11和DBUnit 2.4.9。我试图在保存未指定多对一关系(设置为null)的实体时测试trowing异常。以下是实体: 我创建了以下测试: AbstractDatabaseTest扩展了AbstractTransactionalJUnit4SpringContextTests。 试验方法为: 但是当我做测试的时候 当我像这样将预期异常更改为Da

  • 使用maven,我希望在spring内获得我的项目版本,但不进行过滤。我这样试过 这里建议:在Spring配置文件中访问maven项目版本 如上所述,测试或jetty: run是不可能的。maven仅在打包的存档中生成META-INF。有没有办法指示maven之前生成META-INF,以便您可以启动jetty: run,让Spring从清单中读取项目版本而不会出错?