【问题标题】:Spring Boot : Error :Cannot call sendError() after the response has been committedSpring Boot:错误:提交响应后无法调用 sendError()
【发布时间】:2018-10-12 14:51:37
【问题描述】:

我收到此错误。 响应提交后无法调用 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()

【问题讨论】:

    标签: spring spring-boot jpa spring-data-jpa


    【解决方案1】:

    这是双向关系的问题,因为它们相互引用,在反序列化时,Jackson 在无限循环中运行。我的第一个建议是将@JsonIgnore 添加到关系的一端。

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

    之后,如果这解决了您的问题,您可以查看 @JsonManagedReference/@JsonBackReference 和 @JsonIdentityInfo。

    您也可以查看此link 以了解更多信息

    【讨论】:

    • 在添加 @JsonIgnore 时,我收到此错误 No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 并且没有发现用于创建 BeanSerializer 的属性(为避免异常,请禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS )(通过引用链:com.example.post.postComment.Model.Product["details"]->com.example.post.postComment.Model.Details_$$_jvst4cd_1["handler"])
    • 您可以尝试删除惰性获取类型吗?
    • 那是一篇很棒的文章。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多