JPA

@ManyToOne 양방향 맵핑시 stackoverflowError - lombok @Data를 사용할 경우

기기디 2021. 9. 9. 15:22
@Entity
@Data
@Table(name= "test_a")
public class testA {

    @Id
    @Column
    private String id;

    @OneToMany(mappedBy = "testA"}
    private List<testB> testBList;

}


@Entity
@Data
@Table(name= "test_b")
public class testB{

    @Id
    @Column
    private String id;

    @Column(name = "test_a_id")
    private String testAId;


    @ManyToOne
    @JoinColumn(name = "reference_design_id", referencedColumnName = "id")
    private testA testA;

}

다음과 같이 두 엔티티간 양방향 join을 걸어준 상태에서 testA엔티티를 조회하여 사용하려고하면 

StackOverflow에러가 발생함

@Data annotation위치에서 에러가 발생하였는데. @Data는 .toString()을 호출하게됨.

저렇게 양방향 맵핑이 걸려있을때

 

testA에서 testBList를 toString() -> testB에서 testA를 toString() -> 반복...

 

하게되어 문제가 발생하였다.

 

@JsonManagedReference를 collection type에 적용
@JsonBackReference를 나머지에 적용 시키는 방법으로 해결하려 했으나 

 

testA엔티티 상단 annotion에

@ToString(exclude = "testB")

와 같이 적용시켜 해결하였다