我有一對多的關係,就像你在這裏看到的那樣。我想要做的是我想用學生對象保存學校對象而不設置學生對象的學校。下面的代碼工作,但休眠插入空值到school_id_fk列。休眠時沒有參考的一對多關係
public class Student {
....
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "school_id_fk")
private School school;
}
public class School{
....
@OneToMany(cascade = CascadeType.ALL, mappedBy = "school")
private Set<Student> studentSet = new HashSet<Student>(0);
}
和主要方法;不需要
School school = new School();
school.setSchoolName("school name");
Student student = new Student();
student.setStudentName("studentname1");
student.setStudentSurname("studentsurname1");
//student.setSchool(school); I don't want to set this line
Student student2 = new Student();
student2.setStudentName("studentname2");
student2.setStudentSurname("studentsurname2");
//student2.setSchool(school); I don't want to set this line
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
school.getStudentSet().add(student);
school.getStudentSet().add(student2);
session.save(school);
session.getTransaction().commit();
session.close();
sessionFactory.close();
感謝您的回答。這就是我一直在尋找的:) – hellzone 2015-01-04 14:35:14