![](/img/trans.png)
[英]JHipster Foreign Key in the child table with a bidirectional One to Many relationship is Null
[英]Foreign-key in tb_child is null with bidirectional one-to-many relationship
我正在使用 Java 持久性 API 創建我的第一個 Spring 引導應用程序,以寫入和讀取 postgres 數據庫。 我瀏覽了許多教程和帖子以找出我的確切問題,似乎我目前與兩個實體( Parent
和Child
)具有雙向一對多關系,但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 中有一個具有生成id
的parent
行,在tb_parent
中有一個或多child
行,具有生成的id
和parent_id
列null
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 ,我能夠找到最有效的解決方案。 我必須執行以下步驟:
@Data
注釋(非常感謝,)這基本上避免了為所有屬性生成的 getter 和 setter 方法以及方法 equals()、hashCode()。 Lombok 的 toString() 導致 Stackoverflow 異常。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;
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.