循环依赖双向@OneToMany JPA关系

时间:2018-06-20 11:43:50

标签: java hibernate spring-boot jpa

给出以下两个实体:

@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

}

当我在将虚拟goalRepository.findAll()与虚拟Goal插入后调用Person时,我得到了永无止境的递归循环。 将@JsonIgnore添加到goal的{​​{1}}列表中没有帮助。我也尝试过Person。我想念什么?

1 个答案:

答案 0 :(得分:0)

如果 jackson 引发了异常,请尝试使用以下两个注释:

  • @JsonManagedReference
  • @JsonBackReference

请参阅http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion