Note that there are some explanatory texts on larger screens.

plurals
  1. POHibernate using of @ManyToMany and update both ways
    primarykey
    data
    text
    <p>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</p> <pre><code>public class Room { @ManyToMany private Collection&lt;Student&gt; studentList = new ArrayList&lt;Student&gt;(); } </code></pre> <hr> <pre><code>public class Student { @ManyToMany(mappedBy="studentList") private Collection&lt;Room&gt; roomList = new ArrayList&lt;Room&gt;(); } </code></pre> <p>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</p> <pre><code>Collection&lt;Student&gt; collectionOfStudents=new ArrayList&lt;Student&gt;(); 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); </code></pre> <p>This worked and inserted to table Room_Student</p> <p>When i did</p> <pre><code>Collection&lt;Room&gt; collectionOfRooms=new ArrayList&lt;Room&gt;(); 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); </code></pre> <p>it <strong>did not insert</strong> into table Room_Student for room2 and room3. Thanks for all the replies</p> <p>edited 1: i added</p> <pre><code>public class Student { @ManyToMany(mappedBy="studentList",cascade={CascadeType.ALL}) private Collection&lt;Room&gt; roomList = new ArrayList&lt;Room&gt;(); } </code></pre> <p>This</p> <pre><code>student1.getRoomList().addAll(collectionOfRooms); session.update(student1); </code></pre> <p>did not update/insert the rooms into table</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload