如何通过 Hibernate 在多对多关系中插入关联 table?

How to insert into associative table in many to many relationship by Hibernate?

我有两个具有多对多关系的 table 学生和课程。

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

    ...
    @ManyToMany(mappedBy="students")
    private List<Course> courses = new ArrayList<Course>();

    ...
    // getters and setters
}


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

    ...
    @ManyToMany
    private List<Student> students = new ArrayList<Student>();

    ...
    // getters and setters
}

我正在使用 Hibernate 和 Persistence API 来做映射 假设我在课程 table:

中有 5 门课程
Id  Name
1  Course1
2  Course2
3  Course3
4  Course4
5  Course5

学生 table 从零条记录开始。一旦学生被插入Student table,即

Id  Name
1  Student1

我还需要在 CourseStudent 中插入至少一条记录 table。假设 Stduent1 修了三门课程 Course1、Course2 和 Course3,那么我需要插入:

StudentId CourseID
1         1
1         2
1         3

我现在遇到的困难是,在我的数据模型中,我没有 CourseStudent class,只有 Student 和 Course 及其映射@many_to_many。这个 table CourseStudent 是由 Hibernate 创建和管理的,它的映射 class CourseStudent 似乎是不必要的。

在这种情况下,如何将记录插入模型中没有对象映射的关联 table?我是否必须显式创建一个 class CourseStudent 才能实现此目的,以便我可以将数据持久保存到关联 table 中?

不,你不必这样做。它应该像将课程添加到学生的课程列表并更新(保存)学生一样简单。

但请记住:据我所知,hibernate 无法自行更新双向关系。这意味着您必须将每门课程的学生添加到学生列表中并保存该课程。

希望对您有所帮助