gpt4 book ai didi

hibernate-mapping - 休眠 : Adding a new element to association list does not persist

转载 作者:行者123 更新时间:2023-12-04 09:01:39 24 4
gpt4 key购买 nike

我在两个实体之间有一个多对多关联:类(class)和学生。它们通过 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
}

学生.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",
joinColumns=@JoinColumn(name="STUDENT_REF"),
inverseJoinColumns=@JoinColumn(name="COURSE_REF")
)
private Set<Course> courses = Collections.emptySet();

// Rest of the class, getters, setters etc
}

我想为一门特定类(class) (id=77) 添加学生 (id=11) 列表,如下所示(交易已经开始):
// 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:
当我创建新的 Course 和 Student 对象并保存时,整个持久性对我来说工作得很好。当我检索现有 Course 和现有 Student 对象并在它们之间添加新关联时,不起作用的是。

最佳答案

这就是问题所在。事实证明,我只保存了协会的一侧。这是我应该做的:

// Create new list and add a student to it
Student student_11 = (Student)session.get(Student.class.getName(), 11);
Course course_77 = (Course) session.get(Course.class.getName(), 77);

List studentsList = new ArrayList(1);
studentsList.add(student_11);

Set coursesList = new HashSet(1);
coursesList.add(course_77);

course_77.setStudents(studentsList);
// THIS IS WHAT'S WRONG - I MISSED THIS NEXT LINE
student_11.setCourses(coursesList);

我在 http://en.wikibooks.org/wiki/Java_Persistence/Relationships 找到了答案(在“常见问题”下查看)。

关于hibernate-mapping - 休眠 : Adding a new element to association list does not persist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7750549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com