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