我有兩個實體之間的多對多的關聯:課程和學生。它們通過STUDENT_COURSE_MAP關聯表關聯。休眠:添加新的元素關聯列表不堅持
Course.java:
@Entity
@Table(name="COURSE")
public class Course implements java.io.Serializable {
@ManyToMany(
mappedBy="courses",
cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
private List<Student> students = Collections.emptyList();
// Rest of the class, getters, setters etc
}
Student.java:
@Entity
@Table(name="STUDENT")
public class Student implements java.io.Serializable {
@ManyToMany(
targetEntity=Course.class,
cascade = { CascadeType.PERSIST, CascadeType.MERGE }
)
@JoinTable(
name="STUDENT_COURSE_MAP",
[email protected](name="STUDENT_REF"),
[email protected](name="COURSE_REF")
)
private Set<Course> courses = Collections.emptySet();
// Rest of the class, getters, setters etc
}
我想補充一個學生對一個特定的課程(ID = 11)名單(ID = 77 )如下(交易已經開始):
// Create new list and add a student to it
Student student_11 = (Student) session.get(Student.class.getName(), 11);
List<Student> studentsList = new ArrayList<Student>(1);
studentsList.add(student_11);
// Now, set the list of students in the course
Course course_77 = (Course) session.get(Course.class.getName(), 77);
course_77.setStudents(studentsList);
我節省使用下面的代碼是:
session.flush();
session.getTransaction().commit();
然而,該協會 - course_77和student_11 - 不會被保存到數據庫。在休眠日誌中沒有生成插入語句。
我甚至嘗試調用session.saveOrUpdate(course_77)
。當saveOrUpdate
只調用以下記錄:
allowing proxied method [saveOrUpdate] to proceed to real session
persistent instance of: org.whatra.tradecog.db.entity.Artist
ignoring persistent instance
object already associated with session: [Course#77]
提示/提示/解決方案大加讚賞。
注1: 當我創造新的課程和學生對象,並保存整個持久事情的作品對我蠻好。不起作用的是當我檢索現有課程和現有學生對象並在它們之間添加新的關聯時。
謝謝Hemant。該鏈接描述瞭如何創建新的課程和學生對象並將其保存到持久性存儲/數據庫。這對我來說沒有問題。當我從數據庫中檢索現有課程和現有學生並將其關聯時,什麼都不起作用。你能幫忙嗎? – pballs