Infinite loop with spring-boot in a one to many relation

前端 未结 6 1865
梦谈多话
梦谈多话 2021-02-06 09:52

In a rest application, I use spring boot with jpa.

I have a class Lodger

who have

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, m         


        
6条回答
  •  抹茶落季
    2021-02-06 10:09

    Lets assume your code looks like below :-

    Lodger.class
    
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger")
    private List referenceList;
    
    public List getReferenceList() {
        return referenceList;
    }
    
    public void setReferenceList(List referenceList) {
        this.referenceList = referenceList;
    }
    
    @Override
    public String toString() {
        return "Lodger[referenceList=" + referenceList + "]";
    }
    

    Reference.class

    @ManyToOne
    @JoinColumn(name = "lodgerId")
    private Lodger lodger;
    
    public Lodger getLodger() {
        return lodger;
    }
    
    public void setLodger(Lodger lodger) {
        this.lodger = lodger;
    }
    
    @Override
    public String toString() {
        return "Reference[lodger=" + lodger + "]";
    }
    

    When you notice at the toString() method written in both the POJO's, you will see that we are calling toString() of both the classes from either side which results in infinite no. of calls to toString() method from both sides which never terminates. To avoid this situation remove any the reference from toString() of Refernce.class[You may remove from Lodger class also.] So toString() of Reference class will not have lodger property in it.

    So finally your Reference class will look like :-

    Reference.class

    @ManyToOne
    @JoinColumn(name = "lodgerId")
    private Lodger lodger;
    
    public Lodger getLodger() {
        return lodger;
    }
    
    public void setLodger(Lodger lodger) {
        this.lodger = lodger;
    }
    
    @Override
    public String toString() {
        return "Reference[Properties other than lodger=" + properties other than lodger + "]";
    }
    

提交回复
热议问题