数据不会持久存储到数据库并在控制台中显示空指针异常

时间:2016-01-31 16:28:57

标签: java spring hibernate spring-mvc spring-boot

我是春季启动的初学者,我使用spring boot在数据库上执行CRUD操作。该程序没有错误,但在运行我的应用程序时遇到错误:NullPointerException

这是我的计划: -

CrudOperationApplication.java

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CrudOperationApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrudOperationApplication.class, args);
    }
}

DatabaseCon.java

package com;

import java.util.Properties;
import javax.sql.DataSource;

import org.hibernate.SessionFactory;
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.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ComponentScan({ "com" })
@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:application.properties" })
public class DatabaseCon {

        @Autowired
        private Environment environment;

        @Bean
        public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
            sessionFactory.setDataSource(dataSource());
            sessionFactory.setPackagesToScan(new String[] { "com" });
            sessionFactory.setHibernateProperties(hibernateProperties());
            return sessionFactory;
         }

        @Bean
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
            dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
            dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
            dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
            return dataSource;
        }

        private Properties hibernateProperties() {
            Properties properties = new Properties();
            properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
            properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
            properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
            return properties;       
        }

        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(SessionFactory s) {
           HibernateTransactionManager txManager = new HibernateTransactionManager();
           txManager.setSessionFactory(s);
           return txManager;
        }
    }

Employee.java

package com;

import javax.persistence.*;

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

    @Id
    int id;

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

    @Column(name="salary")
    int salary;

    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 int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
    }


}

EmployeeDao.java

package com;

public interface EmployeeDao {

    String insertValue(Employee e);
    String updateValue(Employee e);
    String deleteValue(Employee e);
    String getValue();
    String getSpecificValue( int id);
}

EmployeeController.java

package com;

import java.util.*;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController implements EmployeeDao{
    HibernateTemplate ht;
    Employee e=new Employee();
    void setHt(HibernateTemplate ht)
    {
        this.ht=ht;
    }

    // for insertion into database

    @RequestMapping(value="/",method=RequestMethod.POST)
    public String insertValue(Employee e)
    {
        e.setId(1);
        e.setName("james");
        e.setSalary(7000);
        ht.persist(e);
        return "value saved to database";
    }

    //for updation

    @RequestMapping(value="/",method=RequestMethod.PUT)
    public String updateValue(Employee e)
    {
        ht.update(e);
        return "value updated to database";
    }

    //for deletion

    @RequestMapping(value="/",method=RequestMethod.DELETE)
    public String deleteValue(Employee e)
    {
        ht.delete(e);
        return "value deleted from database";
    }

    // get stored values from d.b

    @RequestMapping(value="/",method=RequestMethod.GET)
    public String getValue()
    {
        List<Employee> al=new ArrayList<Employee>();

        al=ht.loadAll(Employee.class);
        return ""+al;

    }

    // to get particular value from d.b

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/{id}",method=RequestMethod.GET)
    public String getSpecificValue(@PathVariable int id)
    {
        List<Employee> al=new ArrayList<Employee>();
        al=(List<Employee>) ht.load(Employee.class,id);
        return ""+al;
    }
}

Application.properties

jdbc.driverClassName = org.postgresql.Driver

jdbc.url = jdbc:postgresql://localhost:5432/testc

jdbc.db=testc

jdbc.port=5432

jdbc.ip= 127.0.0.1

jdbc.username = postgres

jdbc.password = root

hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

hibernate.show_sql = true

hibernate.format_sql = true

1 个答案:

答案 0 :(得分:6)

您正在使用Spring Boot,然后使用Spring Boot。目前你正在努力不使用Spring Boot。

首先,而不是手动配置DataSource,让Spring Boot为您完成。移除@Bean的{​​{1}}并在DataSource中添加spring.datasource属性(或只是重命名现有属性)。

application.properties

接下来而不是使用普通的Hibernate我强烈建议开始使用JPA。因此,请删除spring.datasource.url=jdbc:postgresql://localhost:5432/testc spring.datasource.username=postgres spring.datasource.password=root LocalSessionFactoryBean的定义。只需将以下属性添加到您的配置中即可。

HibernateTransactionManager

现在基本上有一个空的配置类,只需将其删除即可。 Spring Boot已经为您组件扫描,创建JPA,启用事务。

在你的控制器/ dao hybrid中(这是一个坏事imho!)而不是spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true 而是使用HibernateTemplate。但是,我建议分离dao和控制器功能。

EntityManager

现在在你的控制器中使用那个dao。

@Repository
@Transactional
public class EmployeeDaoJpa implements EmployeeDao {

    @PersistenceContext
    private EntityManager em;

    // Method implementations using the EntityManager

}

另一个提示不首先使用@RestController public class EmployeeController { private final EmployeeDao dao; @Autowired public EmployeeController(EmployeeDao dao) { this.dao=dao; } // for insertion into database @RequestMapping(value="/",method=RequestMethod.POST) public String insertValue(Employee e) { e.setId(1); e.setName("james"); e.setSalary(7000); dao.insertvalue(e); return "value saved to database"; } //for updation @RequestMapping(value="/",method=RequestMethod.PUT) public String updateValue(Employee e) { dao.updateValue(e); return "value updated to database"; } //for deletion @RequestMapping(value="/",method=RequestMethod.DELETE) public String deleteValue(Employee e) { ht.delete(e); return "value deleted from database"; } // get stored values from d.b @RequestMapping(value="/",method=RequestMethod.GET) public String getValue() { return ""+dao.findAll(); } // to get particular value from d.b @SuppressWarnings("unchecked") @RequestMapping(value="/{id}",method=RequestMethod.GET) public String getSpecificValue(@PathVariable int id) { return ""+dao.findOne(id); } } 作为您的包,它是低级别的,当Spring或您的容器开始扫描com包时,它将扫描com包中的所有内容。就像以com开头的jar文件中的所有内容一样。因此,发明一个更好的包命名。

最后,您现在只拥有控制器,存储库类和接口,最后只有应用程序类。没有更多的配置类完全适合您的com