關于與 JPA 物體的雙向關系的另一個問題:
假設我有以下兩個類:
@Entity
public class Product
{
@Id
private Long productID;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonManagedReference
@JoinColumn(name = "fk_supplier")
private Supplier supplier;
private String description;
public Supplier getSupplier()
{
return supplier;
}
}
和
@Entity
public class Supplier
{
@Id
private Long supplierID;
@OneToMany(mappedBy = "supplier")
@JsonBackReference
private Set<Product> products = new HashSet<>();
private String name;
public Set<Product> getProducts()
{
return products;
}
}
有了這些定義,如果我查詢產品,我就會得到我想要的結果。例如像這樣:
{
"productID": 1,
"supplier": {
"supplierID": 1,
"name": "Acer"
},
"description": "Gaming chair"
}
但如果我反過來做,從而查詢供應商,我只會得到這個:
{
"supplierID": 1,
"name": "Acer"
}
在這里,我錯過了產品。
如何做到這一點?
uj5u.com熱心網友回復:
OneToMany 本質上是惰性的,所以如果你想加載供應商和所有產品,你需要急切地獲取產品
@OneToMany(fetch = FetchType.EAGER)
// or
@Query("select s from Supplier s left join fetch s.products where s.supplierID = 1)
此外,由于您在供應商和產品之間存在回圈依賴關系,因此您在產品集合上使用了 @JsonBackReference,這將阻止產品被序列化為 json,因此您的回應
如果您想回傳帶有產品串列的供應商或帶有供應商的產品并防止回圈依賴問題,請洗掉 @JsonBackReference 和 @JsonManagedReference 參考并改用 @JsonIgnoreProperties @JsonIgnoreProperties("products")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "fk_supplier")
private Supplier supplier;
@JsonIgnoreProperties("supplier")
@OneToMany(mappedBy = "supplier", fetch = FetchType.EAGER)
private Set<Product> products = new HashSet<>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/513449.html
下一篇:無法加入兩個表JPA
