Search code examples
springspring-bootjpaspring-data-jpa

Spring Boot : Error :Cannot call sendError() after the response has been committed


I am getting this error . Cannot call sendError() after the response has been committed Can someone help me figure out why?.

    @Entity
    public class Product {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;

        @OneToOne(
                fetch = FetchType.LAZY,
                cascade = CascadeType.ALL
        )
        @JoinColumn(name = "details_id")
        private Details details;
//Getters and setters left out for brevity
    }


@Entity
public class Details {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String description;
    private float price;
    private float discount;
    @OneToOne(mappedBy = "details")
    private Product product;
}


@RestController
public class ProductController {
    @Autowired
    ProductRepository productRepository;

    @GetMapping("/getAllProducts")
    public Iterable<Product> getAllProducts(){
        return productRepository.findAll();
    }
}

   @RestController
public class DetialsController {
    @Autowired
    ProductRepository productRepository;

    @Autowired
    DetailsRepository detailsRepository;

    @PostMapping("/details")
    public Details addDetails(@RequestBody Details details) {
        Product newProduct = new Product();
        newProduct.setDetails(details);
        productRepository.save(newProduct);
        return detailsRepository.save(details);
    }
}

I am able to make the POST call to /details; for adding details successfully. But when i make GET call to /getAllProducts, I am getting this error Cannot call sendError() after the response has been committed


Solution

  • This is an issue with bidirectional relationships, as they hold references to each other, at deserialization, Jackson runs in an infinite loop. My first suggestion would be adding @JsonIgnore to one end of the relation.

    @OneToOne(mappedBy = "details")
    @JsonIgnore
    private Product product;
    

    Afterward, if that solved your issue, you can look over @JsonManagedReference/@JsonBackReference and @JsonIdentityInfo.

    You can also look over this link for more insight