怎么在保存主表的同时将附表也保存
1 需要给附表对象设置关联的主表,然后再把附表对象设置给主表,最后save主表。
在service中
public void add(Student s){ Set<Course> courses = s.getCourses(); courses.forEach(c->{
//关键 c.setStudent(s); }); studentRepositiry.save(s); }
public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "student_id") private Student student;
//getter setter 省略 }
public class Student implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @OneToMany(cascade = CascadeType.ALL) @JoinTable(name="student_course",joinColumns={@JoinColumn(name="student_id")}, inverseJoinColumns={@JoinColumn(name="course_id")}) private Set<Course> courses; //getter setter 省略}