spring-data-jpa Spring Boot :错误:提交响应后无法调用sendError()

dba5bblo  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(199)

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

6ovsh4lw

6ovsh4lw1#

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

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

之后,如果这解决了您的问题,您可以查看@JsonManagedReference/@JsonBackReference和@JsonIdentityInfo。
您还可以查看此link以获得更多信息

9o685dep

9o685dep2#

您可以使用此选项:

@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;
}

相关问题