循环依赖双向@OneToMany JPA 关系
Posted
技术标签:
【中文标题】循环依赖双向@OneToMany JPA 关系【英文标题】:Circular Dependency bidirectional @OneToMany JPA relationship 【发布时间】:2018-11-29 12:59:53 【问题描述】:给定以下两个实体:
@Entity
public class Goal
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String description;
private BigDecimal amount;
@Email
private String email;
@Email
private String supervisorEmail;
private LocalDateTime deadline;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private PaymentPurpose purpose;
@Enumerated(EnumType.STRING)
private GoalStatus status;
@ManyToOne(cascade = CascadeType.ALL)
private Person person;
//getters and setters
和
@Entity
public class Person
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@Email
private String email;
@OneToMany(mappedBy = "person")
private List<Goal> goals;
//getters and setters
当我在插入一个 Dummy Goal
和一个 Dummy Person
后调用 goalRepository.findAll()
时,我得到一个永无止境的递归循环。
将@JsonIgnore
添加到Person
中的goal
列表没有帮助。我也试过@JsonIgnoreProperties
。我错过了什么?
【问题讨论】:
【参考方案1】:如果 jackson 引发异常,请尝试使用以下两个注解:
@JsonManagedReference @JsonBackReference见http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
【讨论】:
以上是关于循环依赖双向@OneToMany JPA 关系的主要内容,如果未能解决你的问题,请参考以下文章
使用 OnetoMany 和 ManytoOne 映射时的无限递归循环(双向)