sedflix
sedflix

Reputation: 226

@ManyToMany mapping doesn't update the corresponding Tables

My Course class

@Entity
public class Course {

    @Column
    @Id
    private String courseCode;

    ...

    @ManyToMany(fetch = FetchType.EAGER )
    @JoinTable(
            name = "Students_RegisteredCourse",
            joinColumns = {@JoinColumn(name = "courseCode")},
            inverseJoinColumns = {@JoinColumn(name = "email")}
    )
    private Set<Student> registeredStudents = new HashSet<>();


..
..
..
}

My Students class

@Entity
public class Student extends User {
...
@ManyToMany(mappedBy = "registeredStudents")
private List<Course> registeredCourse = new ArrayList<>();
...
}

The user class is a usually Entity.

I'm trying to add courses to registeredCourses while creating new Students. But it is not working out. Course.getCourseByName("Discrete Mathematics") works fine. No new rows are added to Students_RegisteredCourse table on successfully executing this code.

    session.beginTransaction();

    Student temp = new Student();
    temp.setName("Siddharth Yadav");
    temp.setEmail("[email protected]");
    temp.setRollNumber("2016268");
    temp.setPassword("[{Sid@123}]");

    List<Course> cse = new ArrayList<>();
    cse.add(Course.getCourseByName("Discrete Mathematics"));
    cse.add(Course.getCourseByName("Advanced Programming"));
    temp.setRegisteredCourse(cse);

    session.update(temp);
    session.getTransaction().commit();

`

Upvotes: 1

Views: 56

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26572

You have to make sure that each of the Courses also has the registeredStudents filled with the new student:

List<Course> cse = new ArrayList<>();
cse.add(Course.getCourseByName("Discrete Mathematics"));
cse.add(Course.getCourseByName("Advanced Programming"));
temp.setRegisteredCourse(cse);

for(Course course: cse){
    cse.getRegisteredStudents().add(temp);
}

Now the persistence provider will know that there is the mutual manytomany dependency here and perform an insert to the link table.

Also as the Student is created anew here .. you should use persist instead of update:

session.persist(temp);

Upvotes: 1

Related Questions