【发布时间】:2020-02-19 20:33:20
【问题描述】:
我有学生课
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
@ManyToMany(mappedBy = "students", fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH})
private List<Course> courses;
public void addCourse(Course theCourse) {
if (courses == null) {
courses = new ArrayList<>();
}
courses.add(theCourse);
theCourse.addStudents(this);
}
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.PERSIST, CascadeType.REFRESH})
private List<Student> students;
public void addStudents(Student theStudent) {
if (students == null) {
students = new ArrayList<>();
}
students.add(theStudent);
}
}
//definitely I wrote syntax wrong here because i don't copy and paste from code.
Course c =new Course(//fill constrouctor);
CourseRepositoryy.save(c);
student s = new Student(//fill constrouctor);
s.addCourse(c)
StudentRepository.save(s);
or
student s = new Student(//fill constrouctor);
Course c =new Course(//fill constrouctor);
c.addStudents(s);
save(s);
save(c);
现在我想创建学生和课程并将它们保存在连接表中保存每个参考。 我不知道先是哪个,然后再添加另一个。 有人可以帮助我并提供描述该主题的参考资料吗?
【问题讨论】:
标签: hibernate jpa spring-data-jpa repository spring-repositories