【发布时间】:2011-10-28 12:15:37
【问题描述】:
我尝试了一个关于 Hibernate 多对多关系的示例项目,下载自 http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html 然后,当我要向现有学生添加课程时,我遇到了复制同一个学生的问题,但从前面的问题中解决了这个问题。
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
+------------+-----------+
我真的需要这样看待(同一个学生可以做几门课程):
+------------+-----------+
| STUDENT_ID | COURSE_ID |
+------------+-----------+
| 1 | 6 |
| 1 | 7 |
| 2 | 7 |
+------------+-----------+
学生.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;
}
}
课程.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;
}
}
非常感谢您的帮助。
【问题讨论】:
-
@KonstantinPribluda 我现在添加了我的 2 个课程。
标签: java hibernate jakarta-ee many-to-many