I have 3 tables
- Student
- Course
- Enrolled Course (Join Table)
There is a many-to-many relationship between student and course. Since a student can enroll in many courses and a course can have many students enrolled.
I added the corresponding List(students) and Set(courses) in Course and Student entity classes respectively.
The Student
Entity:
@Entity
@Table(name="Student_Tbl")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
private String name;
private String department;
@JoinTable(
name = "enrolled_course",
joinColumns = @JoinColumn(name = "student_id",referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "course_id",referencedColumnName = "title"))
@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private Set<Course> courses;
The Course
Entity:
@Entity
@Table(name="Course_Tbl")
public class Course {
@Id
private String title;
private String description;
@ManyToMany(mappedBy = "courses",fetch = FetchType.EAGER)
private Set<Student> students;
The Controller
Class:
@RestController
@RequestMapping("/v1")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@Autowired
private CourseRepository courseRepository;
@Autowired
private StudentService studentService;
@PostMapping("/student/register")
public ResponseEntity<Student> saveStudent(@RequestBody Student student)
{
studentService.saveStudent(student);
return ResponseEntity.ok(student);
}
}
When I save a Student with a course, it all works well. The data is stored in all the three tables
{
"name":"ABC",
"department":"CS",
"course":[
{
"title":"DBMS",
"description":"Database Management System"
}
]
}
But when I post another request with the same course for different students,
Duplicate entry 'DBMS' for key 'course_tbl.PRIMARY'
error is thrown.
How do I avoid this?
Edit:
public void saveStudent(Student student){
for(Course course : student.getCourse() ){
if(courseRepository.findByTitle(course.getTitle())!= null) continue;
courseRepository.save(course);
}
studentRepository.save(student);
}
Here I manually handled the case by checking if the course is already present in the table which worked as expected.