我是 Hibernate 的新手,我遇到了一个问题。我有两个实体(学生和课程)。学生可以有很多课程,课程可以有很多学生。当我制作一门新课程并将其添加到数据库中时,在同一个会话中,我将此课程添加到学生的课程中(student.getCourses().add(course)),一切正常,并且在课程中都添加了记录表和 Students_Courses 表。当我在另一个方向上做同样的事情时,它不能正常工作。首先,我在数据库中添加一个新学生。我参加了现有的课程并执行 (course.getStudents().add(student)) 但在 Students_Courses 表中没有保存任何记录。多对多映射都是 PERSIST 级联的,所以它必须工作。
你知道问题可能是什么吗?我正在使用 MSSQL 数据库。
第一个方向(不工作 - 只有新学生保存在数据库中)
Session session = HibernateUtils.getSessionFactory().openSession();
session.beginTransaction();
{
Faculty faculty = (Faculty) session.get(Faculty.class, 1);
Student newStudent = new Student();
newStudent.setFaculty(faculty);
newStudent.setGrade(3.0);
newStudent.setName("Some student name");
session.save(newStudent);
Course course = (Course) session.get(Course.class, 1);
course.getStudents().add(newStudent);
// session.update(course); This does not have any effect because the course is persistent anyway
session.getTransaction().commit();
session.close();
}
第二个方向(工作正常 - 新课程和中间表中的记录都保存在数据库中)
Session session = HibernateUtils.getSessionFactory().openSession();
session.beginTransaction();
{
Course newCourse = new Course();
newCourse.setName("Some course name");
session.save(newCourse);
Student student = (Student) session.get(Student.class, 1);
student.getCourses().add(newCourse);
session.getTransaction().commit();
session.close();
}
这是学生实体
@Entity(name = "Students")
public class Student {
@Id
@GeneratedValue
@Column(name = "StudentId")
private int id;
@Column(name = "Name", nullable = false, length = 50)
private String name;
@Column(name = "Grade")
private Double grade = null;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "FacultyId", nullable = false)
private Faculty faculty;
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(
joinColumns = @JoinColumn(name = "StudentId"),
inverseJoinColumns = @JoinColumn(name = "CourseId"))
private Collection<Course> courses;
public Student() {
this.courses = new HashSet<Course>();
}
// Setters and Getters for all fields
}
和课程实体
@Entity(name = "Courses")
public class Course {
@Id
@GeneratedValue
@Column(name = "CourseId")
private int id;
@Column(name = "Name", nullable = false, length = 100)
private String name;
@ManyToMany(mappedBy = "courses", cascade = CascadeType.PERSIST)
private Collection<Student> students;
public Course() {
this.students = new HashSet<Student>();
}
// Setters and Getters for all fields
}