I have this many-many relationship between students and courses as in following JPA models
@Entity(name = "course_result")
public class CourseResult {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;
@ManyToOne(targetEntity = Student.class, cascade = CascadeType.ALL)
@JoinColumn(name = "student_id")
private Student student;
@ManyToOne(targetEntity = Course.class, cascade = CascadeType.ALL)
@JoinColumn(name = "course_id", referencedColumnName = "id")
private Course course;
private float grade;
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;
private String courseName;
private String description;
@OneToMany(mappedBy = "course", fetch = FetchType.EAGER)
private Set<CourseResult> courseResult;
}
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;
private String studentName;
private String studentClass;
@OneToMany(mappedBy = "student", fetch = FetchType.EAGER)
private Set<CourseResult> courseResult;
}
When persisting a CourseResult, I want a new course/student would be created if it not yet exists otherwise they'll be updated only. That's why I set the cascade type to ALL. T
However, it always throws an exception when I try to persist a new CourseResult with existing Student and Course, say both with Id = 1
Student student = studentRepo.findById(BigInteger.ONE).get();
Course course = courseRepo.findById(BigInteger.ONE).get();
CourseResult courseResult = new CourseResult()
.setCourse(course)
.setStudent(student)
.setGrade(1.5F);
courseResultRepository.save(courseResult);
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: org.example.domain.Course; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: org.example.domain.Course
Do you have any idea why?
TIA,