0

我有一对多的关系。如果在课堂上客户我写列表:

private List<Orders> order;

我的 GetMapping 可以正常工作。但我想使用最佳实践,我写的是 Set 而不是 List:

private Set<Orders> order;

结果我有错误:

Could not write JSON: Infinite recursion (StackOverflowError); nested
exception is com.fasterxml.jackson.databind.JsonMappingException: 
Infinite recursion (StackOverflowError)

为什么我有这个错误?赛特有什么问题?

我的实体:

@Entity
public class Customer {
    @Id
    @GeneratedValue
    private int id;
    private String firstName;
    private String lastName;

    @OneToMany(cascade=ALL, mappedBy="customer", orphanRemoval=true)
    private Set<Orders> order;
    //private List<Orders> order;
}

@Entity
public class Orders {
    @Id
    @GeneratedValue
    private int id;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;
}

和获取映射:

@GetMapping("/customer/{id}")
public ResponseEntity get(@PathVariable Long id) {
    Optional<Customer> customer = customerRepository.findById(id);
    return new ResponseEntity<>(new ResponseObject(customer));
}

UPD。我看到问题Infinite Recursion with Jackson JSON and Hibernate JPA issue。但这是另一个问题。我谈谈使用 List 和 Set 的区别。我对@JsonIgnore 不感兴趣,也没有询问它(我在我的代码中使用它)。我想了解为什么我在使用 Set 时出现错误并且在 List 中没有错误

4

0 回答 0