当前位置: 首页 > 知识库问答 >
问题:

" HTTP状态500-servlet spring的Servlet.init()抛出异常"

越鸿才
2023-03-14

嗨,我正在使用Hibernate和Postgresql尝试一个简单的Spring MVC CRUD应用程序。我得到了下面的异常

例外:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.service.EmployeeService com.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.service.EmployeeService com.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao  bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in file [/Users/mohammad.waseem/Downloads/apache-tomcat-8.5.6/webapps/crud/WEB-INF/classes/com/daoImp/EmployeeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)

POM.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com</groupId>
    <artifactId>crud</artifactId>
    <packaging>war</packaging>
    <version>1.0.0-SNAPSHOT</version>
    <name>crud Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <org.springframework.version>3.1.1.RELEASE</org.springframework.version>
    </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>


            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-oxm</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc-portlet</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${org.springframework.version}</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>9.4-1206-jdbc42</version>
            </dependency>
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.2.2</version>
            </dependency>
            <dependency>
                <groupId>commons-pool</groupId>
                <artifactId>commons-pool</artifactId>
                <version>1.6</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.0.1.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
                <version>4.2.0.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate.common</groupId>
                <artifactId>hibernate-commons-annotations</artifactId>
                <version>4.0.1.Final</version>
                <classifier>tests</classifier>
            </dependency>
            <dependency>
                <groupId>org.hibernate.javax.persistence</groupId>
                <artifactId>hibernate-jpa-2.0-api</artifactId>
                <version>1.0.1.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>4.0.1.Final</version>
            </dependency>
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>1.0.0.GA</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.6.4</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.logging</groupId>
                <artifactId>jboss-logging</artifactId>
                <version>3.1.0.CR2</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.6.4</version>
            </dependency>
        </dependencies>
        <build>
            <finalName>crud</finalName>
        </build>
    </project>

在WEB-INF下

网状物xml文件

    <?xml version="1.0" encoding="UTF-8"?>
<web-app
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring-servlet.xml文件

        <beans xmlns:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://www.springframework.org/schema/beans"
           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

    http://www.springframework.org/schema/tx

    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

        <context:component-scan base-package="com"></context:component-scan>
        <tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx: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="/WEB-INF/jsp/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>

        <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">

            <property name="driverClassName" value="org.postgresql.Driver"></property>

            <property name="url" value="jdbc:postgresql://localhost:5433/databasedb"></property>
            <property name="username" value="postgres"></property>
            <property name="password" value="password"></property>
        </bean>

        <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">

            <property name="dataSource" ref="dataSource"></property>
            <property name="annotatedClasses">

                <list>
                    <value>com.model.Employee</value>
                </list>

            </property>
            <property name="hibernateProperties">
                <props>

                    <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.current_session_context_class">thread</prop>
                </props>

            </property>

        </bean>

        <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">

            <property name="sessionFactory" ref="sessionFactory"></property>

        </bean>

    </beans>

com.bean包下的EmployeeBean类

package com.bean;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
public class EmployeeBean {
    private Integer id;
    private String name;
    private Integer age;
    private Long salary;
    private String address;

    public EmployeeBean() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Long getSalary() {
        return salary;
    }

    public void setSalary(Long salary) {
        this.salary = salary;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

com.controller下的EmployeeController类

package com.controller;

import com.bean.EmployeeBean;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView saveEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
        Employee employee = prepareModel(employeeBean);
        employeeService.addEmployee(employee);
        return new ModelAndView("redirect:/add.html");
    }

    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public ModelAndView listEmployees() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("employees", prepareListtoBean(employeeService.listEmployeess()));
        return new ModelAndView("employeeList", map);
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("employees", prepareListtoBean(employeeService.listEmployeess()));
        return new ModelAndView("addEmployee", map);
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView welcome() {
        return new ModelAndView("index");
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public ModelAndView editEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
        employeeService.deleteEmployee(prepareModel(employeeBean));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("employee", null);
        map.put("employees", prepareListtoBean(employeeService.listEmployeess()));
        return new ModelAndView("addEmployee", map);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView deleteEmployee(@ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("employee", prepareEmployeeBean(employeeService.getEmployee(employeeBean.getId())));
        map.put("Employees", prepareListtoBean(employeeService.listEmployeess()));
        return new ModelAndView("addEmployee", map);
    }

    private Employee prepareModel(EmployeeBean employeeBean) {
        Employee employee = new Employee();
        employee.setEmpAddress(employeeBean.getAddress());
        employee.setEmpAge(employeeBean.getAge());
        employee.setEmpName(employeeBean.getName());
        employee.setSalary(employeeBean.getSalary());
        employee.setEmpId(employeeBean.getId());
        employeeBean.setId(null);
        return employee;

    }

    private List<EmployeeBean> prepareListtoBean(List<Employee> employees) {
        List<EmployeeBean> employeeBeanList = null;
        if (employees != null && !employees.isEmpty()) {
            employeeBeanList = new ArrayList<EmployeeBean>();
            EmployeeBean employeeBean = null;
            for (Employee employee : employees) {
                employeeBean = new EmployeeBean();
                employeeBean.setName(employee.getEmpName());
                employeeBean.setSalary(employee.getSalary());
                employeeBean.setAddress(employee.getEmpAddress());
                employeeBean.setAge(employee.getEmpAge());
                employeeBean.setId(employee.getEmpId());
                employeeBeanList.add(employeeBean);
            }
        }
        return employeeBeanList;
    }

    private EmployeeBean prepareEmployeeBean(Employee employee) {
        EmployeeBean employeeBean = new EmployeeBean();
        employeeBean.setAddress(employee.getEmpAddress());
        employeeBean.setAge(employee.getEmpAge());
        employeeBean.setName(employee.getEmpName());
        employeeBean.setSalary(employee.getSalary());
        employeeBean.setId(employee.getEmpId());
        return employeeBean;
    }
}

com下的EmployeeDao类。dao包

包装com.dao;

import com.model.Employee;

import java.util.List;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
public interface EmployeeDao{
    public void addEmployee(Employee employee);
    public List<Employee> listEmployeess();
    public Employee getEmployee(int empid);
    public void deleteEmployee(Employee employee);
}

Imp下的com.dao类

package com.daoImp;

import com.dao.EmployeeDao;
import com.model.Employee;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
    private SessionFactory sessionFactory;

    Transaction tx = sessionFactory.getCurrentSession().beginTransaction();


    public void addEmployee(Employee employee) {
        sessionFactory.getCurrentSession().saveOrUpdate(employee);
    }

    @SuppressWarnings("unchecked")
    public List<Employee> listEmployeess() {
        tx.commit();

        return (List<Employee>) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();

    }

    public Employee getEmployee(int empid) {
        return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
    }

    public void deleteEmployee(Employee employee) {
        sessionFactory.getCurrentSession().createQuery("Delete from Employee where empid=" + employee.getEmpId()).executeUpdate();
    }
}

com.model 下的员工类

package com.model;

import javax.persistence.*;
import java.io.Serializable;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "empid")
    private Integer empId;
    @Column(name = "empname")
    private String empName;
    @Column(name = "empaddress")
    private String empAddress;
    @Column(name = "salary")
    private Long salary;
    @Column(name = "empAge")
    private Integer empAge;

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpAddress() {
        return empAddress;
    }

    public void setEmpAddress(String empAddress) {
        this.empAddress = empAddress;
    }

    public Long getSalary() {
        return salary;
    }

    public void setSalary(Long salary) {
        this.salary = salary;
    }

    public Integer getEmpAge() {
        return empAge;
    }

    public void setEmpAge(Integer empAge) {
        this.empAge = empAge;
    }
}

com.service包下的EmployeeService接口

package com.service;

import com.model.Employee;

import java.util.List;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
public interface EmployeeService {
    public void addEmployee(Employee employee);
    public List<Employee> listEmployeess();
    public Employee getEmployee(int empid);
    public void deleteEmployee(Employee employee);
}

EmployeeServiceImpl class under com.serviceImpl

package com.serviceImpl;

import com.dao.EmployeeDao;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by mohammad.waseem on 21/11/16.
 */
@Service("employeeService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDao employeeDao;
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void addEmployee(Employee employee) {
        employeeDao.addEmployee(employee);
    }

    public List<Employee> listEmployeess() {
        return employeeDao.listEmployeess();
    }

    public Employee getEmployee(int empid) {
        return employeeDao.getEmployee(empid);
    }

    public void deleteEmployee(Employee employee) {
    employeeDao.deleteEmployee(employee);
    }
}

我对MVC了解不多,所以请提前帮助我谢谢

共有3个答案

殷承恩
2023-03-14

堆栈跟踪抱怨

[com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException

构造函数在这里具有误导性,因为您没有为员工Dao Impl实现任何构造器。

我猜问题发生在构建期间,当java/Spring尝试为字段tx执行以下行时。

Transaction tx = sessionFactory.getCurrentSession().beginTransaction();

在此阶段,sessionFactory仍为空,将在稍后阶段自动连接。

您不应该自己与Transaction交互,它是容器(tomcat spring hibernate)的响应权限(调用tx.commit();也应该是狂热的)。建议使用@Transactional注释。

我建议举一个例子,比如

http://howtodoinjava.com/jpa/spring-hibernate-jpa-configuration-example/

梅庆
2023-03-14
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.EmployeeDao com.serviceImpl.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in file [/Users/mohammad.waseem/Downloads/apache-tomcat-8.5.6/webapps/crud/WEB-INF/classes/com/daoImp/EmployeeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.daoImp.EmployeeDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)

我想问题员工对象。检查调试到你的控制器在方法(准备模型)。看看你的整体。在员工类中不存在构造函数,你改变你的方法名称(公共员工get员工(int empid))。慢慢确认你的代码。

裴翰学
2023-03-14

您没有正确处理< code>Transaction,这导致了问题,因此在您的< code>EmployeeDaoImpl中,您需要将< code>Transaction代码移动到< code>addEmployee()和< code>deleteEmployee()中,如下所示:

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
    private SessionFactory sessionFactory;

    public void addEmployee(Employee employee) {
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        sessionFactory.getCurrentSession().saveOrUpdate(employee);
        tx.commit();
    }

    @SuppressWarnings("unchecked")
    public List<Employee> listEmployeess() {
       Session session = sessionFactory.getCurrentSession();
       Transaction tx = session.beginTransaction();
       Criteria criteria = session.createCriteria(Employee.class);
       List<Employee> list = (List<Employee>)criteria.list();
       tx.commit();
       return list;
    }

    public Employee getEmployee(int empid) {
        return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
    }

    public void deleteEmployee(Employee employee) {
      Session session = sessionFactory.getCurrentSession();
      Transaction tx = session.beginTransaction();
      Query query = session.createQuery("Delete Employee where empid=:empid");
      query.setParameter("empid", employee.getEmpId());
      int result = query.executeUpdate();
      tx.commit();
   }
}

作为最佳实践,您可以使用@Transactional注释而不是手动处理事务,您可以查看此处

 类似资料: