My goal was to create a new entity to handle the problem with @ManyToMany relationship. I'm wondering to audit new entity but hibernate does not populate the CourseRegistration-new entity with data.
@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() {}
}
CodePudding user response:
My bet is that you are missing the cascade option on your @OneToMany
annotation. Try the following:
@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
means that the following operation are propagaed to the associated entity (in this case CourseRegistration
): PERSIST, MERGE, REMOVE, REFRESH and DETACH.
CodePudding user response:
You have to mention fetch type in your mappings and also add getter and setter if not added to your entity like below.
@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<>();
}
add below dependency to enable getter and setter with lambok.
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>