尝试将字符串解析为java.util.date时出现空指针异常

时间:2016-12-07 17:25:13

标签: java mysql spring date jdbc

step into方法saveEmployee的图片:

enter image description here我正在学习Spring + JDBC,并尝试将SQL date-datatype作为java.util.Date或java.sql.Date对象加入Java,并运行到空指针异常。

将数据插入导致异常的Employee tabke的主要方法中的代码:

//the following parses date string into java.util.date
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
    EmployeeDAO empDao = (EmployeeDAO)ctx.getBean("employeeDao");
    Employee employee = new Employee();
    employee.setName("Robert");
    //the following parses date string into java.util.date
    employee.setJoining_Date((new SimpleDateFormat("MM/dd/yyyy")).parse("12/30/2016"));
    employee.setSalary(200);
    employee.setsSN("837463");

Employee.java模型类中的setter的定义:

import java.sql.Date

public void setJoining_Date(java.util.Date joining_Date) {
        this.joining_Date = new java.sql.Date(joining_Date.getTime());
}
public void setJoining_Date(Date joining_Date){
        this.joining_Date = joining_Date;
}

方法:

public void saveEmployee(Employee e){
    this.jdbcTemplate.update(this.employee_insert, new Object[]{e.getName(), e.getJoining_Date(), e.getSalary(), e.getsSN()});
    }

例外:

Exception in thread "main" java.lang.NullPointerException
    at com.springdao.EmployeeDaoImpl.saveEmployee(EmployeeDaoImpl.java:49)
    at com.springclient.EmployeeExec.main(EmployeeExec.java:28)

请同时告知有关实施此类代码的最佳做法。

Spring.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation ="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-   
            2.0.xsd">

    <bean id ="dataSource" class        
      ="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name ="driverClassName" value ="com.mysql.jdbc.Driver"/>
      <property name ="url" value ="jdbc:mysql://localhost:3306/branch_db"/>
      <property name ="username" value ="root"/>
      <property name ="password" value ="root"/>
    </bean>

    <bean id ="jdbcTemplate" class               
      ="org.springframework.jdbc.core.JdbcTemplate">
      <property name ="dataSource" ref ="dataSource"/>
    </bean>

    <bean id ="employeeDao" class  ="com.springdao.EmployeeDaoImpl">
      <property name ="jdbcTemplate" ref ="jdbcTemplate"/>
    </bean>

</beans>

0 个答案:

没有答案
相关问题