Issue
I want to convert the following mapping on courseDetails to manyToMany. This is because I get an exception Found shared references to a collection: com.xyz.courseDetails and I assume this happens because the relation is not actually one to many in the database, since there are some course_detail tuples that has multiple courses.
@Entity
@Table(name = "courses")
public class Course
{
@Column(name = "course_detail_id")
private Long extendedCourseDetailId;
...
@OneToMany(fetch = FetchType.LAZY, targetEntity = CourseDetail.class, cascade = CascadeType.ALL)
@JoinColumn(name="id", referencedColumnName="course_detail_id")
private List<CourseDetail> courseDetails = new ArrayList<>();
}
Simply changing the annotation to ManyToMany does not work, JPA somehow couldn't find the related columns. Why? How can I do this?
Solution
What do you think of this :
- Let's assume the entity CourseDetail has as ID :
public class CourseDetail
{
@Id
@Column(name = "cd_id")
private Long courseDetailId;
- So this non tested code might help you.
- where the table "course__course_detail" will be automatically created to hold the relationship with 2 columns : "course_id" and "coursedetail_id".
@Entity
@Table(name = "courses")
public class Course
{
@Id
@Column(name = "c_id")
private Long courseId;
// @Column(name = "course_detail_id") // I comment because I dont understand the purpose
// private Long extendedCourseDetailId;
...
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "course__course_detail",
joinColumns = @JoinColumn(name = "course_id", referencedColumnName="c_id"),
inverseJoinColumns = @JoinColumn(name = "coursedetail_id", referencedColumnName="cd_id"),
)
private List<CourseDetail> courseDetails = new ArrayList<>();
}
PS: NOT TESTED Feel free to tell me more in comments.
Answered By - g.momo
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)