我有2个实体,PurchaseRequest(PR)和PurchaseRequestLineItem(PRLI)。他们遵循典型的关系模式,因为PR有很多PRLI。我已经在PRLI上注释了PRO / @OneToMany,而PRLI带着@ManyToOne回到公关。我可以很好地插入PR,但如果我尝试自己插入PRLI,并引用PR,我会不断收到错误“Column'CheseRequestID'不能为空”。以下是我的代码。我发现如果我删除PRLI purchaseRequest变量中的@JsonIgnore注释,插入将起作用,但是由于无限递归,getAll会失败。我该如何解决这个问题?
JSON(是的,这些ID有效):
{
"PurchaseRequest": {
"Id":658
},
"ProductID": 2,
"Quantity": 1
}
purchase request.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;
purchase request line item.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
@JsonManagedReference私有List lineItems;
@JsonBackReference私人PurchaseRequest purchaseRequest;