Java 使用@ManyToMany休眠并双向更新

Java 使用@ManyToMany休眠并双向更新,java,hibernate,annotations,Java,Hibernate,Annotations,我有两个班,一个教室班和一个学生班。一个房间可以有许多学生,而一个学生也可以有许多房间。因此我使用了@ManyToMany关系 public class Room { @ManyToMany private Collection<Student> studentList = new ArrayList<Student>(); } 未将房间更新/插入表中在您的映射中,房间是拥有方,学生是拥有方。因此,您必须始终将学生添加到房间中,以便在房间和学生之间创建关系。即使

我有两个班,一个教室班和一个学生班。一个房间可以有许多学生,而一个学生也可以有许多房间。因此我使用了@ManyToMany关系

public class Room {
  @ManyToMany
  private Collection<Student> studentList = new ArrayList<Student>();
}

未将房间更新/插入表中

在您的映射中,
房间
是拥有方,
学生
是拥有方。因此,您必须始终将学生添加到房间中,以便在房间和学生之间创建关系。即使使用级联,以相反的方式进行操作也不起作用。您必须始终在ORM中的关系中定义一个拥有方,并始终使用该方本身来创建关系。这进一步阐明了这个问题。此外,如果需要深入研究,您应该阅读JPA/hibernate文档。

在映射中,
房间
是拥有方,
学生
是拥有方。因此,您必须始终将学生添加到房间中,以便在房间和学生之间创建关系。即使使用级联,以相反的方式进行操作也不起作用。您必须始终在ORM中的关系中定义一个拥有方,并始终使用该方本身来创建关系。这进一步阐明了这个问题。此外,如果需要深入研究,您应该阅读JPA/hibernate文档。

感谢Satadru,hibernate不会以另一种方式持续存在,因此我必须删除映射(mappedBy),并且两者都要删除

学生室桌子 和 房间\学生桌子 将创建。这显示房间拥有学生,学生拥有房间 而不仅仅是学生室


不过,OJB在这个特性上工作得很好。

多亏了Satadru,Hibernate不会以另一种方式持久化,因此我必须删除映射(mappedBy),并且两者都可以

学生室桌子 和 房间\学生桌子 将创建。这显示房间拥有学生,学生拥有房间 而不仅仅是学生室

然而,OJB在这个特性上工作得很好

public class Student {
  @ManyToMany(mappedBy="studentList")
  private Collection<Room> roomList = new ArrayList<Room>();
}
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);
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);
public class Student {
  @ManyToMany(mappedBy="studentList",cascade={CascadeType.ALL})
  private Collection<Room> roomList = new ArrayList<Room>();
}
student1.getRoomList().addAll(collectionOfRooms);
session.update(student1);