Spring持续失败,JSON与FK,FK null

时间:2017-12-15 08:49:57

标签: java json spring one-to-many many-to-one

我有2个实体,PurchaseRequest(PR)和PurchaseRequestLineItem(PRLI)。他们遵循典型的关系模式,因为PR有很多PRLI。我在PRLI上注册了一个带有@OneToMany的公关,而PRLI带着@ManyToOne回到公关。我可以很好地插入PR,但是如果我尝试单独插入PRLI,并引用PR,我会不断收到错误" Column' 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;

1 个答案:

答案 0 :(得分:0)

您可以使用两个注释来解决无限递归问题,而无需使用@JsonIgnore: - @JsonManagedReference

- @ JsonBackReference

@JsonManagedReference   private List lineItems;

@JsonBackReference   私人PurchaseRequest purchaseRequest;