Issue
I have a Student model
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany
@JoinTable (name="student_university",
joinColumns=@JoinColumn (name="student_id"),
inverseJoinColumns=@JoinColumn(name="university_id"))
private List<University> universities;
And the University model
@Entity
public class University {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column
private String name;
@ManyToMany
@JoinTable(name="student_university",
joinColumns=@JoinColumn(name="university_id"),
inverseJoinColumns=@JoinColumn(name="student_id"))
private List<Student> students;
I get 2 models and 2 repositories. Since the connection is ManyToMany, the 3 table is automatically generated. How can I get data from this new table if there is no model and repository for it? Perhaps you can write a request somehow from the controller and pass the result to the template?
Solution
Assuming that since you are using spring-boot you already have created the relevant JpaRepositories for your entities, e.g. studentRepository
and universityRepository
.
Load the selected (in the drop down list) Student and University from the database e.g. Lets assume the selected student from the drop down list has #id: 10 and the selected university from the other drop down list has #id: 45
Long studentId = 10L; //retrieve the real value from your controller's request
Student student = studentRepository.findById(studentId);
Long univerityId = 45L; //retrieve the real value from your controller's request
University univeristy = universityRepository.findById(univerityId);
then add the university to the student's university list and save to DB
student.getUniversities().add(university); //make sure your university list is not null else you will get a null pointer exception here
university.getStudents().add(student); // you can also add the student to the university's students list
studentRepository.save(student);
Upon saving the student_university
table should have a new record with the ids of the student and the university.
Answered By - pleft
Answer Checked By - Robin (JavaFixing Admin)