我有 2 个班级,一个 Room 班级和一个 Student 班级。一个房间可以有很多学生,而一个学生也可以有很多房间。因此我使用了@ManyToMany 关系
public class Room {
@ManyToMany
private Collection<Student> studentList = new ArrayList<Student>();
}
public class Student {
@ManyToMany(mappedBy="studentList")
private Collection<Room> roomList = new ArrayList<Room>();
}
因为我想使用 1 个映射表,即 Room_Student,所以我能够将一组学生添加到一个房间。当我尝试将集合添加到学生时,休眠没有保存它。这里是
Collection<Student> collectionOfStudents=new ArrayList<Student>();
Room room1=(Room) session.get(Room.class, 1);
Student student1=(Student) session.get(Student.class, 1);
Student student2=(Student) session.get(Student.class, 2);
collectionOfStudents.add(student1);
collectionOfStudents.add(student2);
room1.getStudentList().addAll(collectionOfStudents)
session.update(room1);
这有效并插入到表 Room_Student
当我这样做的时候
Collection<Room> collectionOfRooms=new ArrayList<Room>();
Student student1=(Student) session.get(Student.class, 1);
Room room2=(Room) session.get(Room.class, 2);
Room room3=(Room) session.get(Room.class, 3);
collectionOfRooms.add(room2);
collectionOfRooms.add(room3);
student1.getRoomList().addAll(collectionOfRooms);
session.update(student1);
它没有插入到 room2 和 room3 的表 Room_Student 中。感谢所有的答复
编辑1:我添加
public class Student {
@ManyToMany(mappedBy="studentList",cascade={CascadeType.ALL})
private Collection<Room> roomList = new ArrayList<Room>();
}
这
student1.getRoomList().addAll(collectionOfRooms);
session.update(student1);
没有更新/插入房间到表中