简体   繁体   English

Hibernate 多对多关系

[英]Hibernate Many to Many relation

I have a problem with Hibernate many to many relationship.我对 Hibernate 多对多关系有疑问。 In the project has two persistence class named Student and Course.在项目中有两个持久化 class 名为 Student 和 Course。 I configure both classes with many to many relationship.我将两个类都配置为多对多关系。 Thats why, hibernate create a third table StudentCourse which I defined this table in student.hbm.xml file between tags.这就是为什么,hibernate 创建第三个表 StudentCourse 我在 student.hbm.xml 文件中定义了这个表标签之间。 When I store student, it works fine.In other words, it store Student information in Student table, studentId and courseId information in Student_Course table and Course information in course table.当我存储学生时,它工作正常。换句话说,它将学生信息存储在学生表中,将学生 ID 和课程 ID 信息存储在 Student_Course 表中,将课程信息存储在课程表中。 However, when I try to store course information, it only update the course table not StudentCourse table.但是,当我尝试存储课程信息时,它只更新课程表而不是 StudentCourse 表。 Therefore, I tried to add them manually (by writing sql query myself.) As you know, "insert into StudentCourse (studentId,courseId) values(?,?) script doesnt work properly in Hibernate. I tried to write script in Hql but, I could not make it. What should I do? I am really confused.因此,我尝试手动添加它们(通过自己编写 sql 查询。)如您所知,“插入 StudentCourse (studentId,courseId) values(?,?) 脚本在 Hibernate 中无法正常工作。我尝试在 Hql 中编写脚本,但是,我来不及了。我该怎么办?我真的很困惑。

Update:更新:

I use mapping file.我使用映射文件。 I configure student.hbm.xml file as follow;我配置 student.hbm.xml 文件如下;

<set name="courses" table="StudentCourse" cascade="all">
        <key column="studentId" />
        <many-to-many class="Course" column="courseId" /> 

</set>

How to configure this file?如何配置这个文件?

It works fine when you store the student because student is the owner of the relationship.存储学生时它工作正常,因为学生是关系的所有者。 Only changes in the owner of the relationship will affect the contents of the join table.只有关系所有者的更改才会影响连接表的内容。

If you mapped it with annotation you need to add InverseJoinTable如果您使用注释映射它,则需要添加 InverseJoinTable

it looks something like this:它看起来像这样:

@ManyToMany
@JoinTable(
name = “studentid”,
joinColumns = { @JoinColumn(name = “studentid”) },
inverseJoinColumns = { @JoinColumn(name = “courseid”) }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM