【发布时间】:2019-06-09 13:10:10
【问题描述】:
我有一个父实体 A,它与实体 B 和实体 C 有多对多的关系,它们映射在 A_B 表和 A_C 表中。在坚持的同时,我只想坚持 A,A_B 和 A_c 而不坚持 B 和 C 。 如果我不使用 cascadetype.all,我会收到“object references an unsaved transient instance - save the transient instance before flushing”错误。 如果我使用 cascade.all 所有表格都会更新。
这是我的父实体 Student(getter 和 setter 存在但未显示)
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int studentId;
......
......
@ManyToMany()
@JoinTable(name = "student_preferredCountry",joinColumns = @JoinColumn(name
= "studentId"),inverseJoinColumns = @JoinColumn(name = "countryId"))
private Set<Country> countries;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "student_preferred_course",joinColumns = @JoinColumn(name
= "studentId"),inverseJoinColumns = @JoinColumn(name = "courseId"))
private Set<Course> courses;
这是我的孩子实体课程
@Entity
public class Course {
private String courseName;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int courseId;
@ManyToMany(mappedBy = "courses")
private List<Student> coursestudents;
这是我的另一个子实体国家
@Entity
public class Country {
@Id
private int countryId;
private String countryName;
@ManyToMany(mappedBy = "countries")
private List <Student> students;
这就是我坚持的方式
public boolean studententry(@RequestBody Student stud){
studentRepository.save(stud);
这是示例 json 请求
{
"studentFname": "fdfd",
"studentMname": "dfdf",
"studentLname": "fdf",
"studentFatherName": "fd",
"studentMotherName": "dfd",
"studentEmail": "dfd",
"studentAddress": "df",
"studentPhone": "df",
"countries": [
{
"countryId": "1",
"countryName": "aus"
},
{
"countryId": "2",
"countryName": "newz"
}
],
"courses": [
{
"course_id": "1",
"course_name": "IELTS"
},
{
"course_id": "2",
"course_name": "TOEFL"
}
]
}
基本上我想添加所有学生属性,student_courses,student_country,但不保留课程和国家/地区表
【问题讨论】:
标签: java hibernate rest spring-boot jpa