关于与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"
}
这里我错过了产品。
如何做到这一点?
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<>();