[英]How to map oneTomany and manyToone correctly in spring boot
[英]How to correctly map a OneToMany relationship in Spring Boot?
你好,我正在做一個 Spring Boot 項目,我有點困惑。 我有一個Product
實體和一個Property
實體,它們看起來像這樣:
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Long id;
@Column
private String name;
@OneToMany(cascade = CascadeType.ALL)
private List<Property> properties;
//getters and setters omitted
}
public class Property {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Long id;
@Column
private String name;
@Column
private String value;
//getters and setters omitted
}
現在我想知道是否還需要在 Propery 實體中指定 ManyToOne 關系,或者這是否足夠好? 在我過去的項目中,我嘗試在兩個實體(雙向)中使用關系,結果一團糟,因為在嘗試從前端檢索數據時,我經常陷入數據的“無限循環”。 我只需要一個單向且簡單的關系,其中單個 Product 可以有多個屬性,然后我可以使用 getProperties() 方法檢索數據。 我是不是理解錯了,或者我的代碼對於我想要做的事情來說是否足夠好?
如果你有一個單向的@OneToMany 關聯,這意味着你只能從外鍵所在的父端訪問關系。 更多細節在這里
雙向關聯應始終在雙方更新,因此 Parent 方應包含 addChild 和 removeChild 組合。 這些方法確保我們始終同步關聯的雙方,以避免對象或關系數據損壞問題。
如果您不需要從屬性中檢索產品,則不需要映射多對一鏈接。 以我的拙見,編寫您真正需要的代碼總是一個好主意。
沒有普遍好的“好”實施,只有更適合您的需求且最容易維護的解決方案。
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Long id;
@Column
private String name;
@OneToMany(mappedBy = "product" ,cascade = CascadeType.ALL)
private List<Property> properties;
}
public class Property {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Long id;
@Column
private String name;
@Column
private String value;
@ManyToOne
private Product prodcut;
}
您還應該注釋關系的 Many 部分(@ManyToOne)
。 並且您還應該在 Product 實體中指定 Property 實體將在 DB 中進行映射( @OneToMany(mappedBy = "product" ,cascade = CascadeType.ALL))
。
檢查上面的代碼進行修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.