簡體   English   中英

tb_child 中的外鍵是 null,具有雙向一對多關系

[英]Foreign-key in tb_child is null with bidirectional one-to-many relationship

我正在使用 Java 持久性 API 創建我的第一個 Spring 引導應用程序,以寫入和讀取 postgres 數據庫。 我瀏覽了許多教程和帖子以找出我的確切問題,似乎我目前與兩個實體( ParentChild )具有雙向一對多關系,但child列的外鍵始終是null當我寫入數據庫時。

父實體:

@Entity
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "tb_parent")
public class Parent {
    @Schema(description = "id of the parent")
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Schema(description = "child-list of the application")
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch=FetchType.LAZY, orphanRemoval = true)
    private Set<Child> children;
}

子實體:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "tb_child")
public class Child{
    @Schema(description = "id of the child")
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference
    @ManyToOne(targetEntity = Parent.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id", updatable = true, insertable = true)
    private Parent parent;
}

家長服務:

...
    @Override
    public Parent create(Parent parent) {
        log.info("save new parent: {}", parent);
        return parentRepo.save(parent);   // the repo is an interface that extends the JpaRepository
    }
...

調用create方法后,我在 tb_parent 中有一個具有生成idparent行,在tb_parent中有一個或多child行,具有生成的idparent_idnull tb_child

盡管我能找到很多描述類似問題的帖子,但我還沒有找到適合我的解決方案。

更新#1:

一個常見的建議是在所有child元素中手動設置parent object。 但是,由於循環結構,這會導致 Stackoverflow 異常。

    public void setChildren(Set<Child> children) {
        children.forEach(child -> child.setParent(this));
        this.children = children;
    }

此外,感覺有點不對勁,因為幾乎所有內容都由 JPA 注釋自動管理,然后您必須手動同步數據。

感謝Georgy Lvov ,我能夠找到最有效的解決方案。 我必須執行以下步驟:

  1. 按照Georgy Lvov的建議刪除@Data注釋(非常感謝,)這基本上避免了為所有屬性生成的 getter 和 setter 方法以及方法 equals()、hashCode()。 Lombok 的 toString() 導致 Stackoverflow 異常。
  2. 注釋Set<Child> children; 帶有@JsonManagedReference注釋的Parent class 中的變量。 見下文:
    @JsonManagedReference
    @Schema(description = "child-list of the application")
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch=FetchType.LAZY, orphanRemoval = true)
    private Set<Child> children;
  1. 注釋private Parent parent; 在帶有@JsonBackReference注釋的Child class 中。 見下文:
    @JsonBackReference
    @ManyToOne(targetEntity = Parent.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id", updatable = true, insertable = true)
    private Parent parent;

當您創建openapi.json文件時, @JsonBackReference似乎也避免了循環結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM