@ManyToOne 没有填写 parent id 字段

@ManyToOne not filling the parent id field

我在 parent 和 child 实体之间有 many-to-one 双向关系。问题是,当我坚持 child 时,parent_id 没有坚持。其他字段都很好,但 parent_id 保持在 NULL。我将 Spring Data JPA 与 Hibernate 和 mapstruct 一起使用,以在实体和 dto 之间进行转换(如果有帮助的话)。

java 个文件如下:

@Entity
@Table(name = "Parent")
public class ParentEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;


    @OneToMany (fetch = FetchType.LAZY, mappedBy="parent_entity", cascade = { CascadeType.ALL })
    private List<Child> children;

}


@Entity
@Table(name = "Child")
public class ChildEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToOne(optional = true)
    @JoinColumn(nullable = true, name = "parent_entity_id", insertable = false, updatable = false)
    private Parent parent_entity;
}

我已经尝试了一堆 SO 的答案,但现在无济于事。

据我所知。您必须在 parent 和 child 中相互添加。仅将 children 添加到列表中似乎不起作用。

尝试一下,看看是否能解决问题。

由于您使用的是双向关系,因此您现在有责任为您的 child 设置 parent。并删除 insertable = false.