ManyToOne 关系不会填充新实体

ManyToOne relationship does not populate new entity

我的目标是创建一个新实体来处理@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() {}
}

您必须在您的映射中提及获取类型,如果没有像下面那样添加到您的实体中,还需要添加 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>

我敢打赌,您的 @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。