无法使用Spring Boot连接到PostgreSQL数据库来添加和更新值

时间:2019-04-21 14:12:34

标签: spring postgresql spring-boot spring-data-jpa

我正在尝试从PostgreSQL数据库更新“学生”,但它只会删除旧值并为新学生创建一个新的id值,而所有其他字段均为空。

这里是“学生”类,来自“持久性”包,“实体”子包:

@Entity

@Table(name = "student")

public class Student {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "student_id_seq")
@SequenceGenerator(name="student_id_seq", sequenceName = "student_id_seq", allocationSize=1)
@Column(name = "id", nullable = false)
private Integer id;

@Column
private String studentName;

@Column
private Integer studentGroup;

@Column
private String courseName;

@Column
private Integer studentGrades;


public Integer getId() {
    return id;
}

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

public String getStudentName() {
    return studentName;
}

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

public Integer getStudentGroup() {
    return studentGroup;
}

public void setStudentGroup(Integer group) {
    this.studentGroup = group;
}

public String getCourseName() { return courseName;}

public void setCourseName(String courseName) {this.courseName = courseName;}

public Integer getStudentGrades() {
    return studentGrades;
}

public void setStudentGrades(Integer grades) {
    this.studentGrades = grades;
}
}

这是我的“存储库”子包(也来自“持久性”包)的界面,如下所示:

public interface StudentRepository extends JpaRepository<Student, Integer> {}

在“ StudentService”(“商务”包)中,我具有用于创建,更新,删除和查看我拥有的所有学生的操作:

@Service
public class StudentService {

@Inject
StudentRepository studentRepository;

public List<Student> getAllStudentssWithCourses()
{
    return studentRepository.findAll();
}

public Student create(Student newStudent)
{
    return studentRepository.save(newStudent);
}

public void update(Student newStudent, Student oldStudent){
    if(oldStudent == null){
        System.out.println("ERROR! Student does not exist !!!");
    } else{
        newStudent.setId(oldStudent.getId());
        newStudent.setStudentName(newStudent.getStudentName());
        newStudent.setStudentGroup(newStudent.getStudentGroup());
        newStudent.setCourseName(newStudent.getCourseName());
        newStudent.setStudentGrades(newStudent.getStudentGrades());
        studentRepository.save(newStudent);
    }
}


public void delete(Student student){
    studentRepository.delete(student);
}
}

在“控制器”包中,我有:

@Controller
public class StudentController {

@Inject
StudentService studentService;

@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView getStudents()
{
    List<Student> studentList = studentService.getAllStudentssWithCourses();

    ModelAndView mav = new ModelAndView("student_view");
    mav.addObject("studentsWithCoursesList", studentList);
    mav.addObject("newStudent", new Student());
    return mav;

}


@RequestMapping(value = "/student", method = RequestMethod.POST)
public ModelAndView postStudent(@RequestParam(value = "action") String action,@ModelAttribute(value = "newStudent") Student newStudent)
{
    if(action.equals("Create Student"))
        studentService.create(newStudent);
    else if(action.equals("Update Student"))
        studentService.update(new Student(), newStudent);
    else
        studentService.delete(newStudent);
    return new ModelAndView("redirect:student");
}
}

我的html中的“ student_view”看起来像:

 <body background = "https://www.itmagazine.us/wp-content/uploads/2017/10/6f6499a403cf64afea180b6419def4ef.jpg">

 <h1>Welcome, student user !</h1>
 <table  border="1">
 <thead>
 <tr>
  <th>student.ID</th>
  <th>student.NAME</th>
  <th>student.GROUP</th>
  <th>student.COURSE</th>
  <th>student.GRADES</th>
 </tr>
 </thead>
 <tbody>
 <tr th:each="student : ${ studentsWithCoursesList }">

  <td th:text="${ student.id }">ID</td>
  <td th:text="${ student.studentName }"></td>
  <td th:text="${ student.studentGroup }"></td>
  <td th:text="${ student.courseName }"></td>
  <td th:text="${ student.studentGrades }"></td>
  </td>
 </tr>
 </tbody>
 </table>

 <br/>
 <br/>
 <br/>

  <form   th:object="${newStudent}" method = "POST">
  <div class="col-sm-12">
    <label>Student ID</label>
    <input type = "text" th:field="*{id}"/>
  </div>
  <div class="col-sm-12">
    <label>Student Name</label>
    <input type = "text" th:field="*{studentName}"/>
  </div>
  <div class="col-sm-12">
    <label>Student Group</label>
    <input type = "text" th:field="*{studentGroup}"/>
  </div>
  <div class="col-sm-12">
    <label>Course Name</label>
    <input type = "text" th:field="*{courseName}"/>
  </div>
  <div class="col-sm-12">
    <label>Student Grades</label>
    <input type = "text" th:field="*{studentGrades}"/>
  </div>

 <button type="submit" class = "btn btn-primary" name = "action" value="Create Student">ADD Student</button>
 <button type="submit" class = "btn btn-primary" name = "action" value="Update Student">EDIT Student</button>
 <button type="submit" class = "btn btn-primary" name = "action" value="Delete Student">DELETE Student</button>
 </form>
 </body>

我的主要班级:

@SpringBootApplication()

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

   }
}

在我的“ application.properties”中,我有:

spring.jpa.database = POSTGRESQL
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = validate
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation = true


spring.datasource.driverClassName = org.postgresql.Driver
spring.datasource.url = jdbc:postgresql://localhost:5432/ps2
spring.datasource.username = postgres
spring.datasource.password = root

spring.thymeleaf.cache = false

spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

server.port = 8090

我在PostgreSQL中的数据库:

CREATE TABLE public.student
(
    id integer NOT NULL,
    student_name character varying COLLATE pg_catalog."default",
    student_group integer,
    course_name character varying COLLATE pg_catalog."default",
    student_grades integer,
    CONSTRAINT "Student_pkey" PRIMARY KEY (id)
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.student
OWNER to postgres;
-----
CREATE SEQUENCE public.student_id_seq;

ALTER SEQUENCE public.student_id_seq
    OWNER TO postgres;

最后,在“ pom.xml”中,我有:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
</parent>


<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>


    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>


    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901-1.jdbc4</version>
    </dependency>

</dependencies>


<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


</project>

2 个答案:

答案 0 :(得分:0)

这个问题已经被问过了。

最后,您应该使用:

<span style="font-size: large;">Foobar</span>

这是因为IDENTITY仅可用于以下数据库:

Sybase,My SQL,MS SQL Server,DB2和HypersonicSQL。

请参见https://stackoverflow.com/a/29028369/6884722

答案 1 :(得分:0)

GenerationType.IDENTITY依靠数据库自动递增列来生成ID。

以dB表示的Student.id列显然不会自动增加。

我认为自Postgres10起,就可以使用自动递增的标准语法

PostgreSQL Autoincrement

有关不同生成策略的介绍,另请参见https://thoughts-on-java.org/jpa-generate-primary-keys/。 还有以下问题How to choose the id generation strategy when using JPA and Hibernate

总结SEQUENCE是最好的选择, 当您无法使用SEQUENCE时,IDENTITY只是一个不错的选择,因为它会禁用JDBC批处理更新。