休眠多对多级联删除

2022-09-01 15:25:28

我的数据库中有 3 个表:、 和StudentsCoursesStudents_Courses

学生可以有多个课程,课程可以有多个学生。和 之间存在多对多关系。StudentsCourses

我的项目和课程有3个案例添加到我的表格中。Courses

  • (a)当我添加用户时,它被保存得很好,
  • (b)当我为学生添加课程时,它会在预期行为中创建新行。User_Courses
  • (c) 当我试图删除学生时,它正在删除 和 中的相应记录,但它也删除了不需要的记录。即使我在课程中没有任何用户,我也希望课程在那里。StudentsStudents_CoursesCourses

下面是我的表和注释类代码。

    CREATE TABLE `Students` (
    `StudentID` INT(11) NOT NULL AUTO_INCREMENT,
    `StudentName` VARCHAR(50) NOT NULL 
    PRIMARY KEY (`StudentID`)
)

CREATE TABLE `Courses` (
    `CourseID` INT(11) NOT NULL AUTO_INCREMENT,
    `CourseName` VARCHAR(50) NOT NULL 
    PRIMARY KEY (`CourseID`)
)

CREATE TABLE `Student_Courses` (
    `StudentId` INT(10) NOT NULL DEFAULT '0',
    `CourseID` INT(10) NOT NULL DEFAULT '0',
    PRIMARY KEY (`StudentId`, `CourseID`),
    INDEX `FK__courses` (`CourseID`),
    INDEX `StudentId` (`StudentId`),
    CONSTRAINT `FK__courses` FOREIGN KEY (`CourseID`) REFERENCES `courses` (`CourseID`) ON DELETE NO ACTION,
    CONSTRAINT `FK_students` FOREIGN KEY (`StudentId`) REFERENCES `students` (`StudentId`)
)

这是Hibernate生成的Java代码:

@Entity
@Table(name = "Students")
public class Students implements java.io.Serializable {

    private Integer StudentID;
     private String Students;
    private Set<Courses> Courseses = new HashSet<Courses>(0);

    public Students() {
    }


    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "StudentID", unique = true, nullable = false)
    public Integer getStudentID() {
        return this.StudentID;
    }

    public void setStudentID(Integer StudentID) {
        this.StudentID = StudentID;
    }

    @Column(name = "Students", nullable = false, length = 50)
    public String getCampaign() {
        return this.Students;
    }

    public void setCampaign(String Students) {
        this.Students = Students;
    }


 @ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    @JoinTable(name = "Student_Courses", joinColumns = {
        @JoinColumn(name = "StudentId", nullable = false, updatable = false)}, inverseJoinColumns = {
        @JoinColumn(name = "CourseID", nullable = false, updatable = false)})
    public Set<Courses> getCourseses() {
        return this.Courseses;
    }

     public void setCourseses(Set<Courses> Courseses) {
        this.Courseses = Courseses;
    }

    }


    @Entity
@Table(name = "Courses")
public class Courses implements java.io.Serializable {

  private Integer CourseID;
    private String CourseName;
     private Set<Students> Studentses = new HashSet<Students>(0);

    public Courses() {
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "CourseID", unique = true, nullable = false)
    public Integer getCourseID() {
        return this.CourseID;
    }

    public void setCourseID(Integer CourseID) {
        this.CourseID = CourseID;
    }

     @Column(name = "CourseName", nullable = false, length = 100)
    public String getCourseName() {
        return this.CourseName;
    }

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

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "Courseses")
    public Set<Students> getStudentses() {
        return this.Studentses;
    }

    public void setStudentses(Set<Students> Studentses) {
        this.Studentses = Studentses;
    }

    }

我怎样才能实现我所描述的?我无法在网上找到任何合理的文档。


答案 1

我在类似的场景中找到了正确的映射(并用JUnit进行了广泛的测试)。我不认为我会发布测试代码,因为适应这个例子需要很长时间。无论如何,关键是:

  • 不对批注使用属性,请使用联接列mappedBy
  • 列出可能的排除CascadeTypesREMOVE

在OP的例子中

@ManyToMany(fetch = FetchType.LAZY,
        cascade =
        {
                CascadeType.DETACH,
                CascadeType.MERGE,
                CascadeType.REFRESH,
                CascadeType.PERSIST
        },
        targetEntity = Course.class)
@JoinTable(name = "XTB_STUDENTS_COURSES",
        inverseJoinColumns = @JoinColumn(name = "COURSE_ID",
                nullable = false,
                updatable = false),
        joinColumns = @JoinColumn(name = "STUDENT_ID",
                nullable = false,
                updatable = false),
        foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT),
        inverseForeignKey = @ForeignKey(ConstraintMode.CONSTRAINT))
private final Set<Course> courses = new HashSet<>();

@ManyToMany(fetch = FetchType.LAZY,
        cascade =
        {
                CascadeType.DETACH,
                CascadeType.MERGE,
                CascadeType.REFRESH,
                CascadeType.PERSIST
        },
        targetEntity = Student.class)
@JoinTable(name = "XTB_STUDENTS_COURSES",
        joinColumns = @JoinColumn(name = "COURSE_ID",
                nullable = false,
                updatable = false),
        inverseJoinColumns = @JoinColumn(name = "STUDENT_ID",
                nullable = false,
                updatable = false),
        foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT),
        inverseForeignKey = @ForeignKey(ConstraintMode.CONSTRAINT))
private final Set<Student> students = new HashSet<>();

广泛的 JUnit 测试验证了:

  • 我可以为学生添加课程,反之亦然
  • 如果我从学生中删除了课程,则不会删除该课程
  • 反之亦然
  • 如果我删除了一个学生,所有课程都会被分离,但它们仍然保留在数据库中(对其他学生)
  • 反之亦然

答案 2

根据你告诉我的内容,你不希望在学生的getCourseses方法上使用cascade=CascadeType.ALL。请记住,休眠级联与数据库级联不同。即使您没有任何级联,Hibernate也会删除Students_Courses记录。

考虑 Hibernate 级联的最佳方式是,如果对某个实体调用一个操作,并且该操作列在级联列表中,则该操作将在所有子实体上调用。

例如,当您对学生调用 delete 时,由于 delete 位于课程的级联列表中,因此 Hibernate 将对该学生引用的每个课程实体调用 delete。这就是您看到课程记录消失的原因。

不要担心数据库级联,Hibernate会自己处理这些。


推荐