pakcikkantin
pakcikkantin

Reputation: 101

Hibernate using of @ManyToMany and update both ways

I have 2 classes, a Room class and a Student class. A Room can have many Students, while a Student also can have many Rooms. Therefore i used @ManyToMany relationship

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

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

Since i want to use 1 mapping table that is Room_Student, i was able to add a collection of Students to a Room. When I tried to add collection to a Student, hibernate did not save it. Here it is

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);

This worked and inserted to table Room_Student

When i did

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);

it did not insert into table Room_Student for room2 and room3. Thanks for all the replies

edited 1: i added

public class Student {
  @ManyToMany(mappedBy="studentList",cascade={CascadeType.ALL})
  private Collection<Room> roomList = new ArrayList<Room>();
}

This

student1.getRoomList().addAll(collectionOfRooms);
session.update(student1);

did not update/insert the rooms into table

Upvotes: 1

Views: 4355

Answers (2)

pakcikkantin
pakcikkantin

Reputation: 101

Thanks Satadru, Hibernate does not persist the other way, therefore i have to remove the mapping (mappedBy) , and both

Student_Room table and Room_Student table will be created. This shows Room owns Students and Students owns Rooms instead of Student_Room only

Yet the OJB work well this feature.

Upvotes: 0

Satadru Biswas
Satadru Biswas

Reputation: 1595

In your mappings, the Room is the owning side and Student is the owned side. So you will always have to add students to a room in order to create relationships between rooms and students. Doing it the opposite way will not work, even if you use Cascading. You will always have to define a owning side in the relationship in ORM and always use that side itself to create the relationships. This link shed further light on the topic. Also, you should go through the JPA/hibernate documentations if you need to dive deeper.

Upvotes: 4

Related Questions