gpt4 book ai didi

java - 如何在hibernate中连接ManyToMany映射中的中间表

转载 作者:行者123 更新时间:2023-12-02 08:59:37 25 4
gpt4 key购买 nike

有没有办法可以在 ManyToMany 表中加入中间表。您可以考虑 https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html 给出的示例

enter image description here

作为上面 StudentCourse 多对多关系的示例,我们可以有表 STUDENTCOURSESTUDENT_COURSE

我的问题是检查是否有任何方法可以在 java 的 hibernate 中提供此功能,以便 Student 类具有 STUDENT_COURSE 中间表而不是 的映射类(class)表?

我想修改下面的类以获得上面的输出:-

@Entity
@Table(name = "STUDENT")
public class Student {

private long studentId;
private String studentName;
private Set<Course> courses = new HashSet<Course>(0);

public Student() {
}

public Student(String studentName) {
this.studentName = studentName;
}

public Student(String studentName, Set<Course> courses) {
this.studentName = studentName;
this.courses = courses;
}

@Id
@GeneratedValue
@Column(name = "STUDENT_ID")
public long getStudentId() {
return this.studentId;
}

public void setStudentId(long studentId) {
this.studentId = studentId;
}

@Column(name = "STUDENT_NAME", nullable = false, length = 100)
public String getStudentName() {
return this.studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_COURSE",
joinColumns = { @JoinColumn(name = "STUDENT_ID") },
inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
public Set<Course> getCourses() {
return this.courses;
}

public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}

最佳答案

简短回答:

您应该将多对多关联划分为两个多对一关联,并使用 @Embedded 注释为中间实体定义复合键请查看下面的链接了解详细信息

https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/

长答案:

实际上,当您使用@ManyToMany注释在hibernate中建立多对多关联时,它会在幕后创建另一个表来建立ManyToMany关联,该表是在代码中使用@JoinTable注释定义的,对该表的查询完全由hibernate管理要实现多对多关联,并且您没有映射到该表的实体。除非您在中间表(此处为 STUDENT_COURSE)中需要额外的列,或者您想要以与其他实体相同的方式对该表执行某些特定查询,并且想要访问类(class)和学生表的 Id,否则这很好。在 CourseStudent 表中。因为当 hibernate 在后台创建中间表时,您的程序中没有映射到该表的实体,因此您不能为该表拥有其他列,并且您不能将该表视为程序中的实体。如果您需要额外的列,您可以将 @ManyToMany 关联划分为两个 @ManyToOne 关联。这里你应该有另一个名为 StudentCourse 的实体,它有两个 @ManyToOne 关联,一个与 Student 实体,另一个与 Course 实体。但是,当您以这种方式定义多对多关联时,您应该考虑数据完整性,例如,您的 Student_course 表中的 Student_id 和 course_id 的组合是唯一的,实际上它应该是您的 Student_course 表中的复合键。幸运的是,hibernate 和 jpa 中有一些注释提供了这种功能。在这个答案中编写针对这种情况的所有代码是多余的,因为下面的链接中已经有一个很好的示例。

https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/

关于java - 如何在hibernate中连接ManyToMany映射中的中间表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com