gpt4 book ai didi

java - 数据未持久保存到数据库并在控制台中显示空指针异常

转载 作者:行者123 更新时间:2023-12-01 07:52:20 26 4
gpt4 key购买 nike

我是 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;
}
}

员工.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;
}
}

应用程序属性

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

最佳答案

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

首先,让 Spring Boot 为您配置数据源,而不是手动配置数据源。删除@Bean对于 DataSource并添加spring.datasource您的 application.properties 中的属性(或者简单地重命名现有的)。

spring.datasource.url=jdbc:postgresql://localhost:5432/testc
spring.datasource.username=postgres
spring.datasource.password=root

接下来,我强​​烈建议开始使用 JPA,而不是使用普通的 Hibernate。因此删除 LocalSessionFactoryBean 的定义和HibernateTransactionManager 。只需将以下属性添加到您的配置中即可。

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

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

在你的 Controller /dao 混合体中(恕我直言,这是一件坏事!)而不是 HibernateTemplate使用EntityManager反而。不过我建议将 dao 和 Controller 功能分开。

@Repository
@Transactional
public class EmployeeDaoJpa implements EmployeeDao {

@PersistenceContext
private EntityManager em;

// Method implementations using the EntityManager

}

现在在您的 Controller 中使用该 dao。

@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);
}
}

另一个提示不要使用com因为你的包首先是低级别的,当 Spring 或你的容器开始扫描 com 时包它将扫描 com 中的所有内容包裹。就像 jar 文件中以 com 开头的所有内容一样。因此发明一个更好的包命名。

最后,您现在只有 Controller 、存储库类和接口(interface),最后是应用程序类。您的 application.properties 中不再有配置类.

关于java - 数据未持久保存到数据库并在控制台中显示空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com