Issue
I have a Client class which contains a list of Cars in a OneToMany relationship. When I try to GET all clients using Postman, the first client will be printed in the response recursively. How can i get the JSON response with the Client and its corresponding car list, without getting the client from the Car response too?
The Car class
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String model;
private String color;
@ManyToOne(fetch = FetchType.LAZY)
private Client client;
The Client class
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int age;
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "client")
private List<Car> carList;
Image with the response in Postman
Solution
Assume you use Jackson
to serialise to JSON , you can use @JsonIgnoreProperties
to break the cycles:
Car:
@Entity
@Table(name= "Car")
public class Car {
[.....]
@JsonIgnoreProperties("carList")
private Client client;
[...]
}
Client:
@Entity
@Table(name="client")
public class Client {
[....]
@JsonIgnoreProperties("client")
private List<Car> carList;
[...]
}
Answered By - Ken Chan
Answer Checked By - Timothy Miller (JavaFixing Admin)