Hi,
Example of a many-to-many relationship:
A student can be in n departments
A department can have m students.
The simplified mapping code looks like this:
Code:
@Entity
@Table(name="DEPARTMENT")
public class Department {
@ManyToMany(mappedBy="departments", fetch=FetchType.LAZY, cascade= CascadeType.MERGE)
@JoinTable(name="DEPARTMENT_STUDENT",
joinColumns=
@JoinColumn(name="DEPARTMENT_ID", referencedColumnName="DEPARTMENT_ID"),
inverseJoinColumns=
@JoinColumn(name="STUDENT_ID", referencedColumnName="STUDENT_ID")
)
private final List<Student> students= new ArrayList<Student>();
public List<Student> getStudents() {
return students;
}
}
@Entity
@Table(name = "STUDENT")
public class Student {
@ManyToMany(mappedBy = "students", fetch = FetchType.LAZY, cascade= CascadeType.MERGE)
private final List<Department> departments = new ArrayList<Department>();
public List<Department> getDepartments() {
return departments;
}
}
Note that the mapping is set to lazy because I don't need to get all students and departments.
When I want to add a new student to an existing department I would program something link this:
Code:
Department department;
Student student;
//...
department.getStudents().add(student);
student.getDepartments().add(department);
Here is my problem:
When I call department.getStudents(), the students List of the department object is queried from the database.
This has a noticeable performance impact (memory and execution time) if a department has many students.
Everything I really want to do at this point is to add a new record into the mapping table for department and students.
Is there a way to add to a lazy bidirectional many-to-many relationship without retrieving one or both ends of the relationship?