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

时间:2014-03-16 11:13:04

标签: java spring hibernate

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

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/annotation/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>

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

1 个答案:

答案 0 :(得分:0)

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

您的HibernateConfig课程已注明@Configuration。这表明它应该由Spring 管理,您在上下文文件中正确执行

<bean class="org.ligadesportiva.resources.HibernateConfig"/>
但是,你并没有在任何地方使用它。您还没有声明UsuarioHome bean。相反,您自己创建这些对象

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

你如何期望Spring处理它们?

浏览the documentation of Spring IoC container以了解如何通过上下文配置管理这些依赖项。