将单对多双向关系更改为多对多双向关系

时间:2021-02-10 09:13:52

标签: java spring hibernate jpa

我想将 courseDetails 上的以下映射转换为 manyToMany。 这是因为我得到一个异常 Found shared references to a collection: com.xyz.courseDetails 我假设发生这种情况是因为数据库中的关系实际上不是一对多的,因为有一些 course_detail 元组有多个课程。

@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<>();
}

简单地将注释更改为 ManyToMany 是行不通的,JPA 以某种方式找不到相关列。为什么?我该怎么做?

1 个答案:

答案 0 :(得分:1)

你怎么看:

  • 假设实体 CourseDetail 的 ID 为:
public class CourseDetail
{ 
    @Id
    @Column(name = "cd_id")
    private Long courseDetailId;
  • 因此,这段未经测试的代码可能对您有所帮助。
    • 其中将自动创建表“course__course_detail”以保存与 2 列的关系:“course_id”和“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:未测试 欢迎在评论中告诉我更多。