I have following:
@Data
@Entity
@Table(name = "floor")
public class Floor {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "floor_id")
private Long id;
@JsonIgnoreProperties(value= {"floor", "registrations"})
@OneToMany (mappedBy = "floor", cascade = CascadeType.ALL)
private Set<Slot> slots;
}
@Entity
@Table(name = "slot")
public class Slot {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "slot_id")
private Long id;
@ManyToOne
@JoinColumn(name = "floor_id")
private Floor floor;
}
@RestController
public class Controller {
@Autowired
FloorService floorService;
@GetMapping("/api/floors")
public List<Floor> getAllFloors() {
// calls repository.findAll()
return floorService.getAllFloors();
}
}
When accessing API endpoint, I get:
2021-03-06 06:52:30.038 WARN 699889 --- [tp1028811481-19] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.veebzone.parking.model.Floor["slots"])]
By getting list of each floor with /api/floors endpoint, my goal is to get list of slots associated with each floor within their JSON element.
What is the best practice to achieve this:
- My approach is correct, just some configuration issue?
- I should use some DTO returned by a service instead (that has the slots list as a child element) and use JSONIgnore for the slots field.
- Something else