由于sessionFactory.getCurrentSession()导致的java.lang.NullPointerException

时间:2013-07-29 14:26:26

标签: java spring hibernate nullpointerexception sessionfactory

我正在使用Spring和Hibernate制作Java webapp,但是当我执行它时,我有这个错误:

SEVERE: El Servlet.service() para el servlet [springapp] en el contexto con ruta [/appCracks] lanzó la excepción [Request processing failed; nested exception is java.lang.NullPointerException] con causa raíz
java.lang.NullPointerException
    at com.companyname.springapp.repository.UsuarioDaoImp.getTodosUsuariosList(UsuarioDaoImp.java:26)
    at com.companyname.springapp.service.SimpleAnonimoManager.identificarse(SimpleAnonimoManager.java:21)
    at com.companyname.springapp.web.IdentificarseFormController.onSubmit(IdentificarseFormController.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    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:472)
    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:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    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(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

当我尝试获取会话时,错误就在这一行:

    return this.sessionFactory.getCurrentSession().createQuery("from Usuario u order by u.id").list();

我在这里复制了那个错误所涉及的类:

UsuarioDaoImp.java

package com.companyname.springapp.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.companyname.springapp.domain.Usuario;

@Repository(value = "usuarioDao")
public class UsuarioDaoImp implements UsuarioDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Usuario> getTodosUsuariosList() {
        return this.sessionFactory.getCurrentSession()
                .createQuery("from Usuario u order by u.id")
                .list();
    }

    @Override
    public String encriptarContrasena(String contrasena) {
        return (String) this.sessionFactory.getCurrentSession()
                .createQuery("select SHA1(:c)")
                .setParameter ( "c", contrasena)
                .uniqueResult();
    }

    @Override
    public String getTipoUsuario(String usuario) {
        return (String) this.sessionFactory.getCurrentSession()
                .createQuery("select u.tipoUsuario from Usuario u where u.usuario = '" +
                usuario + "'")
                .uniqueResult();
    }


}

SimpleAnonimoManager.java:

package com.companyname.springapp.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.companyname.springapp.domain.Usuario;
import com.companyname.springapp.repository.UsuarioDao;

@Component
public class SimpleAnonimoManager implements AnonimoManager {

    private static final long serialVersionUID = 1L;

    @Autowired
    private UsuarioDao usuarioDao;

    @Override
    public boolean identificarse(String nombreUsuario, String contrasena) {
        List<Usuario> usuarios = usuarioDao.getTodosUsuariosList();
        if (usuarios != null) {
            for (Usuario usuario : usuarios) {
                if (usuario.getUsuario().equals(nombreUsuario)) {
                    if (usuario.getContrasena().equals(usuarioDao.encriptarContrasena(contrasena))) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public String getTipoUsuario(String usuario) {
        return usuarioDao.getTipoUsuario(usuario);
    }

}

IdentificarseFormController.java:

package com.companyname.springapp.web;

import java.util.Calendar;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.companyname.springapp.service.AdminManager;
import com.companyname.springapp.service.GmcracksManager;
import com.companyname.springapp.service.Identificarse;
import com.companyname.springapp.service.AnonimoManager;

@Controller
@RequestMapping(value="/identificarse.htm")
public class IdentificarseFormController {

    @Autowired
    private AnonimoManager anonimoManager;

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, @Valid Identificarse identificarse, BindingResult result) {

        String usuario = identificarse.getUsuario();
        String contrasena = identificarse.getContrasena();

        boolean IdentificacionOK = anonimoManager.identificarse(usuario, contrasena);

        if (IdentificacionOK) {
            request.getSession().setAttribute("nombreUsuario", usuario);
            String tipoUsuario = anonimoManager.getTipoUsuario(usuario);
            request.getSession().setAttribute("tipoUsuario", tipoUsuario);
            return new ModelAndView (new RedirectView("hello.htm"));
        }
        else {
            request.getSession().setAttribute("error", "Usuario o contraseña incorrectos");
            return new ModelAndView (new RedirectView ("identificarse.htm"));
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    protected Identificarse formBackingObject(HttpServletRequest request) throws ServletException {
        Identificarse identificarse = new Identificarse();
        return identificarse;
    }

配置文件是这样的: APP-config.xml中

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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">

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
    </bean>

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.companyname.springapp.web" />

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>        
    </bean>

</beans>

的applicationContext.xml:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <!-- holding properties for database connectivity /-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- enabling annotation driven configuration /-->
    <context:annotation-config/>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.companyname.springapp.repository" />
    <context:component-scan base-package="com.companyname.springapp.service" />

</beans>

hibernate.cfg.xml中:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="com.companyname.springapp.repository.UsuarioDaoImp" />
    </session-factory>

</hibernate-configuration>

我也尝试映射作为数据库中实体的类Usuario.java,但我遇到了同样的问题。

问题是当我试图获得会话时。我被告知使用OpenSessionInViewFilter,并使用SessionFactoryUtil而不是SessionFactory,但我不知道如何使用它。

有人可以帮帮我吗?感谢

1 个答案:

答案 0 :(得分:2)

您的sessionFactory尚未在UsuarioDaoImp中设置。尝试使用构造函数自动装配,而不是使用setSessionFactory,例如

@Repository(value = "usuarioDao")
public class UsuarioDaoImp implements UsuarioDao {

    private final SessionFactory sessionFactory;

    @Autowired
    public UsuarioDaoImp(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    ...

}