Hibernate Many to Many relation
I have a problem with Hibernate many to many relationship. In the project has two persistence class named Student and 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. 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. However, when I try to store course information, it only update the course table not StudentCourse table. Therefore, I tried to add them manually (by writing sql query myself.) As you know, "insert into StudentCourse (studentId,courseId) values(?,?) script doesnt 开发者_JAVA百科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.
Update:
I use mapping file. I configure student.hbm.xml file as follow;
<set name="courses" table="StudentCourse" cascade="all">
<key column="studentId" />
<many-to-many class="Course" column="courseId" />
</set>
How to configure this file ?
If you mapped it with annotation you need to add InverseJoinTable
it looks something like this:
@ManyToMany
@JoinTable(
name = “studentid”,
joinColumns = { @JoinColumn(name = “studentid”) },
inverseJoinColumns = { @JoinColumn(name = “courseid”) }
)
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.
精彩评论