Hibernate多対多リレーションシップに関するサンプルプロジェクトを試しました http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html それから、既存のものにコースを追加するときに同じ学生を複製するという問題がありました学生は、しかし、ここに入れられた前の質問からそれを解決しました。Hibernate多対多既存行をマージする
Hibernate Many-to-Many, duplicates same record
は、だから今、私のようなコード:
Set<Course> courses = new HashSet<Course>();
courses.add(new Course("Science"));
DB db = new DB();
Student eswar= db.getStudentFromId(1);
eswar.setCourses(courses);
session.saveOrUpdate(eswar);
、同じ学生Eswarがあります。
+------------+--------------+
| STUDENT_ID | STUDENT_NAME |
+------------+--------------+
| 1 | Eswar |
| 2 | Joe |
+------------+--------------+
しかしstudent_courseテーブルがちょうどCourse_IDにに新しい値で更新が、新しいコースを追加していません。
+------------+-----------+
| STUDENT_ID | COURSE_ID |
+------------+-----------+
| 1 | 7 | //it was 6 last time
+------------+-----------+
本当にこのようにこれを確認するために必要なI(同じ生徒がいくつかのコースを行うことができます):
+------------+-----------+
| STUDENT_ID | COURSE_ID |
+------------+-----------+
| 1 | 6 |
| 1 | 7 |
| 2 | 7 |
+------------+-----------+
Student.Java
@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;
}
}
Course.java
@Entity
@Table(name="COURSE")
public class Course {
private long courseId;
private String courseName;
public Course() {
}
public Course(String courseName) {
this.courseName = courseName;
}
@Id
@GeneratedValue
@Column(name="COURSE_ID")
public long getCourseId() {
return this.courseId;
}
public void setCourseId(long courseId) {
this.courseId = courseId;
}
@Column(name="COURSE_NAME", nullable=false)
public String getCourseName() {
return this.courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
本当にありがとうございます。
注釈を指定してください –
@ ConstantinPribluda今すぐ2つのクラスを追加しました。 –