Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot

前端 未结 7 1389
时光说笑
时光说笑 2020-12-08 23:18

This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes ple

7条回答
  •  萌比男神i
    2020-12-08 23:50

    I've been struggling with the same problem for days, I tried @JsonIgnore, @JsonManagedReference and @JsonBackReference annotation, and even @JsonIdentityInfo annotation and none of them have worked.

    If you (the future readers ) are in the same situation, the solution is easier than you expected, simply put @JsonIgnore or @JsonManagedReference / @JsonBackReference on the attribute's getter and not on the attribute itself. And that will do.

    Here's a simple example how to do so :

    Say we have two classes, Order and Product, and OneToMany relation between them.

    Order class

    public class Order{
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private String id_order;
      private double price;
      @OneToMany(mappedBy = "order")
      @LazyCollection(LazyCollectionOption.FALSE)
      private List products
      //constructor, getters & setter 
    }
    

    Product Class:

    public class Product{
       @Id
       @GeneratedValue(strategy = GenerationType.AUTO)
       private String id_product;
       private String name;
       @ManyToOne
       @JoinColumn(name = "id_order")
       private Order order;
       //consturctor, getters & setters
     }
    

    So in order to use @JsonManagedReference and @JsonBackReference, just add them to the getters as the following :

    public class Order{
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private String id_order;
      private double price;
      @OneToMany(mappedBy = "order")
      @LazyCollection(LazyCollectionOption.FALSE)
      private List products
      //constructor, getters & setter 
      @JsonManagedReference
      public List getProducts(){
        return products;
    }
    

    Product class:

    public class Product{
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private String id_product;
      private String name;
      @ManyToOne
      @JoinColumn(name = "id_order")
      private Order order;
      //consturctor, getters & setters
      @JsonBackReference
      public Order getOrder(){
        return order;
      }
     }
    

提交回复
热议问题