获取java.lang.NullPointerException而getSession()。save(entity);

时间:2014-03-25 07:52:24

标签: java hibernate spring-mvc nullpointerexception

我想添加对象数据并希望保存在数据库表中,一切正常但它给我一个错误:

java.lang.NullPointerException

getSession().save(entity);

我在代码中调用了这个方法:

@Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {

    @Autowired
    private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void Process(AddCategory command){        
        PatronCategory entity = new PatronCategory();
        entity.setCategoryName(command.getCategoryName());
        try
        {
            patronCategoryRepository.save(entity);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

以下是我的xml文件:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:5432/abc"/>
        <property name="username" value="postgres"/>
        <property name="password" value="pwd"/>
        <property name="validationQuery" value="SELECT 1"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.ngl.domain"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.generate_statistics">true</prop>
            </props>
        </property>
    </bean>

    <!-- Transaction Manager -->
    <bean id="txManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

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

这是一个getSession()方法:

@Override
    public Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

这是一个sessionFactory声明:

protected SessionFactory sessionFactory;

任何猜测为什么它是NULLPOINTEREXCEPTION ??

更新:

java.lang.NullPointerException
    at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
    at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
    at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
    at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
    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.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    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:915)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
    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)

4 个答案:

答案 0 :(得分:3)

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

和xml for transaction manager

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

    <tx:annotation-driven transaction-manager="txManager" />
存储库中的

@Autowired
protected SessionFactory sessionFactory;

答案 1 :(得分:0)

您的配置有点不完整。您应该将会话管理完全委托给Spring

添加spring xml文件:

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

然后,在您的PatronCategoryRepository类中,扩展HibernateDaoSupport并添加此构造函数:

public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{

    @Autowired
    public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
        super();
        super.setHibernateTemplate(hibernateTemplate);
    }
    [...]
}

在AddCategoryProcessor中,保留存储库的定义如下:

@Autowired
private IPatronCategoryRepository patronCategoryRepository;

最后你的方法:

@Override
@Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){        
    PatronCategory entity = new PatronCategory();
    entity.setCategoryName(command.getCategoryName());
    try
    {
        getHibernateTemplate.save(entity);
    }catch (Exception e){
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

如果您仍然需要访问SessionFactory,您唯一需要做的就是将其注入PatronCategoryRepository:

@Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{

    @Autowired
    protected SessionFactory sessionFactory;


    public PatronCategoryRepository() {
    }

    public PatronCategory save(PatronCategory entity){
        return getSession().save(entity);
    }

    private Session getSession() {
       return sessionFactory.getCurrentSession();
    }
}

请记住从AddCategoryProcessor中删除新子句,将其保留为:

@Autowired
private IPatronCategoryRepository patronCategoryRepository; 

答案 3 :(得分:0)

Employee.java

package com.javacodegeeks.snippets.enterprise.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Employee1")
public class Employee implements Serializable {

    @Id
    @Column(name = "ID")
    private int id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "AGE")
    private int age;

    public Employee() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

EmployeeDao.java

package com.javacodegeeks.snippets.enterprise.dao;

import com.javacodegeeks.snippets.enterprise.model.Employee;

public interface EmployeeDAO {

          public void saveEmployee(Employee employee);

          Employee findEmployeeById(int id);

          void updateEmployee(Employee employee);

          void deleteEmployee(Employee employee);

}


EmployeeDaoImpl.java

package com.javacodegeeks.snippets.enterprise.dao;

import java.io.Serializable;

import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.javacodegeeks.snippets.enterprise.model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO {
    private HibernateTemplate template;

    private SessionFactory sessionFactory;

    @Autowired
    public void setTemplate(HibernateTemplate template) {

        this.template = template;
        // template.setSessionFactory(sessionFactory);

    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        new HibernateTemplate(sessionFactory);
    }

    /*
     * public void saveEmployee(Employee employee) {
     * sessionFactory.getCurrentSession().save(employee);
     * 
     * }
     */

    public Employee findEmployeeById(int id) {
        return (Employee) sessionFactory.getCurrentSession().get(
                Employee.class, id);
    }

    public void updateEmployee(Employee employee) {
        sessionFactory.getCurrentSession().update(employee);

    }

    public void deleteEmployee(Employee employee) {
        sessionFactory.getCurrentSession().delete(employee);

    }

    public void saveEmployee(Employee employee) {

        sessionFactory.getCurrentSession().persist(employee);
        template.saveOrUpdate(employee);

    }
}


Application COntext.xml

<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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

  <context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />

 <!--  <tx:annotation-driven/> -->

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="root" />
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
     <property name="annotatedClasses">  
        <list>  
        <value>com.javacodegeeks.snippets.enterprise.model.Employee</value>  
        </list>  
        </property> 

      <!-- <property name="mappingResources">  
        <list>  
        <value>Employee.hbm.xml</value>  
        </list>  
        </property>  -->


    <property name="hibernateProperties">
      <props>
        <prop 
         key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>

  </bean>

  <!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean> -->
  <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">  
    <property name="sessionFactory" ref="sessionFactory"></property>  
    </bean> 
   <bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">  
    <property name="template" ref="template"></property>  
    </bean>  
</beans>


pleas ehelp me :-)