无法在Spring Boot中插入ManyToMany关系的记录。

问题描述 投票:0回答:1

我知道有很多关于这个问题的帖子,我已经尝试了他们的解决方案,但仍然无法解决我的问题。我已经启动了一个Spring Boot应用程序,它连接到postgesql数据库。我有两个名为学生和课程的类。我想在它们之间创建一个ManyToMany关系。当我运行这个应用程序时,它按照我的要求创建了表。而且,如果我插入一个记录为course_student表,我可以显示一个学生采取的课程。但是我可以为一个学生添加一个新的课程,但是什么都没有发生。

学生课程

package com.example.demo.models;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column(nullable = false)
    private String lastName;

    @ManyToMany(
        fetch = FetchType.LAZY,
        cascade = {
                CascadeType.ALL,
        },
        mappedBy = "students"
    )
    private Set<Course> courses = new HashSet<>();

    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Set<Course> getCourses() {
        return courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}

课程班

package com.example.demo.models;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "courses")
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @ManyToMany(
        fetch = FetchType.LAZY,
        cascade = {
            CascadeType.ALL,
        }
    )
    @JoinTable(
        name = "course_student",
        joinColumns = { @JoinColumn(name = "course_id") },
        inverseJoinColumns = { @JoinColumn(name = "student_id") }
    )
    private Set<Student> students = new HashSet<>();

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }
}

IStudentRepository

package com.example.demo.repositories;

import com.example.demo.models.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface IStudentRepository extends JpaRepository<Student, Long> {
}

SqlStudentService类

package com.example.demo.services;

import com.example.demo.models.Course;
import com.example.demo.models.Student;
import com.example.demo.repositories.IStudentRepository;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("SqlStudentService")
public class SqlStudentService implements IStudentService {
    private final IStudentRepository studentRepository;

    public SqlStudentService(IStudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public List<Student> getStudents() {
        return studentRepository.findAll(Sort.by(Sort.Direction.ASC, "id"));
    }

    public Student getStudentById(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

    public Student insertStudent(Student student) {
        return studentRepository.save(student);
    }

    public Student updateStudent(Long id, Student student) {
        Student oldStudent = getStudentById(id);

        if (oldStudent != null) {
            oldStudent.setFirstName(student.getFirstName());
            oldStudent.setLastName(student.getLastName());

            return studentRepository.save(oldStudent);
        }
        return null;
    }

    public void deleteStudentById(Long id) {
        studentRepository.deleteById(id);
    }

    public void addStudentToCourse(Course course, Long studentId) {
        Student student = getStudentById(studentId);

        if (student != null) {
            student.getCourses().add(course);
            studentRepository.save(student);
        }
    }
}

SqlStudentService类中的所有其他函数都能正常工作,但addStudentToCourse方法不能。我已经在学生.getCourses().add(course);行后返回学生对象。课程添加成功了。但是它没有被添加到course_student表中的记录中。你有什么想法,我错过了什么?非常感谢您。

java postgresql spring-boot many-to-many
1个回答
0
投票
 @ManyToMany
 @JoinTable(name = "course_student", joinColumns = { @JoinColumn(name = "course_id_fk", referencedColumnName   ="course_id_pk") },
inverseJoinColumns = { @JoinColumn(name = 
   "student_id_fk",referencedColumnName="student_id_pk") })

private Set<Student> students;

你不需要使用Cascading Type =All和fetch type,因为它是懒惰的默认值。

© www.soinside.com 2019 - 2024. All rights reserved.