0

I have one to many relationship. If in class Customer I write List:

private List<Orders> order;

my GetMapping will work fine. But I want to use best practices and I write Set instead of List:

private Set<Orders> order;

In result I have error:

Could not write JSON: Infinite recursion (StackOverflowError); nested
exception is com.fasterxml.jackson.databind.JsonMappingException: 
Infinite recursion (StackOverflowError)

Why I have this error? What's wrong with Set?

My entities:

@Entity
public class Customer {
    @Id
    @GeneratedValue
    private int id;
    private String firstName;
    private String lastName;

    @OneToMany(cascade=ALL, mappedBy="customer", orphanRemoval=true)
    private Set<Orders> order;
    //private List<Orders> order;
}

@Entity
public class Orders {
    @Id
    @GeneratedValue
    private int id;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;
}

And GetMapping:

@GetMapping("/customer/{id}")
public ResponseEntity get(@PathVariable Long id) {
    Optional<Customer> customer = customerRepository.findById(id);
    return new ResponseEntity<>(new ResponseObject(customer));
}

UPD. I see question Infinite Recursion with Jackson JSON and Hibernate JPA issue. But it's other question. I talk about difference in use List and Set. I am not interesting in @JsonIgnore and I don't ask about it (and I use it in my code). I want to understand why I have an error when I use Set and don't have error with List

vesnaves
  • 45
  • 1
  • 5
  • Possible duplicate of [Infinite Recursion with Jackson JSON and Hibernate JPA issue](https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue) – Alien Oct 02 '18 at 15:08
  • No it's not a duplicate, because I talk about difference in use List and Set. I am not interesting in @JsonIgnore and I don't ask about it (and I use it in my code). I want to understand why I have an error when I use Set and don't have error with List – vesnaves Oct 02 '18 at 15:13
  • There shouldn't be any difference regarding StacOverflow errors between the two. For more help, post the stack trace of the exception, and the complete relevant code. Note that Orders should really, really be named Order, since an instance of Order is **one** Order. – JB Nizet Oct 02 '18 at 15:33

0 Answers0