I'm using Spring Boot to create a restful API along with JPA. I'm having problems when trying to get results using GET request with ResponseEntity to generate a JSON. Looks like it's returning an infinite JSON..
Code:
@GetMapping("/machines")
public ResponseEntity<List<Machine>> getMachines() {
List<Machine> result = this.machineRepository.findAll();
return new ResponseEntity<>(result, HttpStatus.OK);
Error:
[nio-8080-exec-1] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/main/machines] and exception [Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.hibernate.collection.internal.PersistentSet[0]->com.main.example.model.SoftwareCode["machines"]->org.hibernate.collection.internal.PersistentSet[0]->com.main.example.model.Machine["softwareCodes"]->org.hibernate.collection.internal.PersistentSet[0]->com.
- Also, here's some background of what I persisted to DB, to give you some context
Machine.java:
@Entity
public class Machine {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
private String name;
@ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable(
name = "software_codes",
joinColumns = @JoinColumn(name = "machine_id"),
inverseJoinColumns = @JoinColumn(name = "software_id"))
private Set<SoftwareCode> softwareCodes = new HashSet<>();
public Machine(String name, Set<SoftwareCode> softwareCodes) {
this.name = name;
this.softwareCodes = softwareCodes;
}
SoftwareCode.java:
@Entity
public class SoftwareCode {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
private String code;
@ManyToMany(mappedBy = "softwareCodes", cascade = {CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.EAGER)
private Set<Machine> machines;
public SoftwareCode(String code) {
this.code = code;
}
My approach to persist to DB:
Set<Machine> machines = new HashSet<>();
Set<SoftwareCode> softwareCodes = new HashSet<>();
SoftwareCode softwareCode = new SoftwareCode("ABC");
SoftwareCode softwareCode2 = new SoftwareCode("XYZ");
softwareCodes.add(softwareCode);
softwareCodes.add(softwareCode2);
Machine machine = new Machine("machine1", softwareCodes);
machines.add(machine);
vehicleRepository.saveAll(machines);