我的目標是創建一個新物體來處理@ManyToMany 關系的問題。我想審核新物體,但 hibernate 不會用資料填充 CourseRegistration-new 物體。
@Entity
@Table(name = "course_registration")
public class CourseRegistration {
@Id
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
public CourseRegistration() {}
}
@Entity
@Table(name = "student")
public class Student {
@Id
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "student")
private List<CourseRegistration> registrations = new ArrayList<>();
public Student() {}
}
@Entity
@Table(name = "course")
public class Course {
@Id
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "course")
private List<CourseRegistration> registrations = new ArrayList<>();
public Course() {}
}
uj5u.com熱心網友回復:
我敢打賭,您在@OneToMany注釋中缺少級聯選項。請嘗試以下操作:
@Entity
@Table(name = "course")
public class Course {
@Id
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<CourseRegistration> registrations = new ArrayList<>();
public Course() {}
}
ALL意味著以下操作被傳播到關聯物體(在本例中CourseRegistration):PERSIST、MERGE、REMOVE、REFRESH 和 DETACH。
uj5u.com熱心網友回復:
您必須在映射中提及獲取型別,如果未添加到您的物體中,還需要添加 getter 和 setter,如下所示。
@Entity
@Table(name = "course_registration")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CourseRegistration {
@Id
@Column(name = "id")
private Long id;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnore
@JoinColumn(name = "student_id")
private Student student;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnore
@JoinColumn(name = "course_id")
private Course course;
}
@Entity
@Table(name = "student")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@Id
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "student")
private List<CourseRegistration> registrations = new ArrayList<>();
}
@Entity
@Table(name = "course")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Course {
@Id
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "course")
private List<CourseRegistration> registrations = new ArrayList<>();
}
添加以下依賴項以使用lambok啟用getter和setter。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342763.html
上一篇:如何解決bean創建程序中的意外例外;嵌套例外是java.lang.IllegalStateException:MethodhastoomanyBodyparameters
