我正在使用 Java Persistence API 創建我的第一個 Spring Boot 應用程式,以寫入和讀取 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方法后,我在其中有parent一行,其中tb_parent有一個生成的id,一個或多個child行,其中tb_child有一個生成的id和一個列的null值parent_id。
盡管我能找到很多描述類似問題的帖子,但我還沒有找到適合我的解決方案。
Update #1:
A common suggestion is to manually set the parent object in all child elements. However, this results in a Stackoverflow Exception due to the circular structure.
public void setChildren(Set<Child> children) {
children.forEach(child -> child.setParent(this));
this.children = children;
}
Additionally, it kinda feels off because almost everything is managed automatically by the JPA Annotations and then you have to manually sync the data.
uj5u.com熱心網友回復:
感謝Georgy Lvov,我能夠找到最有效的解決方案。我必須執行以下步驟:
- 按照Georgy Lvov的建議洗掉
@Data注釋(非常感謝!)這基本上避免了 Lombok 為所有屬性生成的 getter 和 setter 方法以及方法 equals()、hashCode() 和 toString() 導致 Stackoverflow 例外。 - 用注解對類中的
Set<Child> children;變數進行注解。見下文:Parent@JsonManagedReference
@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;在Child類中@JsonBackReference注解。見下文:
@JsonBackReference
@ManyToOne(targetEntity = Parent.class, fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id", referencedColumnName = "id", updatable = true, insertable = true)
private Parent parent;
創建檔案@JsonBackReference時似乎也避免了回圈結構。openapi.json
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424555.html
