
[英]Spring boot : java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
[英]Spring Boot : Error :Cannot call sendError() after the response has been committed
我收到这个错误。 提交响应后无法调用 sendError()有人可以帮我找出原因吗?
@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);
}
}
我可以对 /details 进行 POST 调用; 成功添加详细信息。 但是当我对 /getAllProducts 进行 GET 调用时,我收到此错误无法在响应提交后调用 sendError()
这是双向关系的问题,因为它们相互引用,反序列化时,Jackson无限循环运行。 我的第一个建议是在关系的一端添加@JsonIgnore
。
@OneToOne(mappedBy = "details")
@JsonIgnore
private Product product;
之后,如果这解决了您的问题,则可以查看@ JsonManagedReference / @ JsonBackReference和@JsonIdentityInfo。
您也可以查看此链接以获得更多信息
你可以使用这个:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@JsonBackReference(value = "details_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;
@JsonManagedReference(value = "details")
@OneToOne(mappedBy = "details",,cascade=CascadeType.ALL)
private Product product;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.