我有2个实体,PurchaseRequest(PR)和PurchaseRequestLineItem(PRLI)。他们遵循典型的关系模式,因为PR有许多PRLI。我在PRLI上用@OneToMany注释了PR,然后在@PR上用@ManyToOne注释了PRLI。我可以很好地插入PR,但是如果我尝试自己插入PRLI(引用PR),则会不断出现错误“列'PurchaseRequestID'不能为空”。下面是我的代码。我发现如果删除PRLI PurchaseRequest变量中的@JsonIgnore批注,则插入将起作用,但是由于无限递归,getAll失败。我该如何解决?
JSON(是,这些ID有效):
{
"PurchaseRequest": {
"Id":658
},
"ProductID": 2,
"Quantity": 1
}
PurchaseRequest.java:
@Entity
@Table(name="purchaserequest")
public class PurchaseRequest implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name="UserID")
private User user;
....
@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="purchaserequestid")
private List<PurchaseRequestLineItem> lineItems;
PurchaseRequestLineItem.java
@Entity
@Table(name="purchaserequestlineitem")
public class PurchaseRequestLineItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name="PurchaseRequestID")
@JsonIgnore
private PurchaseRequest purchaseRequest;
private int productID;
private int quantity;
最佳答案
您可以使用两个注释来解决无限递归问题,而无需使用@JsonIgnore:
-@ JsonManagedReference
-@ JsonBackReference
@JsonManagedReference
私人List lineItems;
@JsonBackReference
私人PurchaseRequest PurchaseRequest;