🤖스프링 부트에서 양방향 연관 관계를 맺고 있는 객체를 그대로 view로 보낼 경우 양방향 무한 참조 문제를 일으키게 됩니다.
이에 대한 해결 방법은 아래와 같습니다.
@Entity
public class EntityA {
@JsonIgnore
@ManyToOne
private EntityB entityB;
}
@Entity
public class EntityB {
@ManyToOne
private EntityA entityA;
}
🫡위의 경우
@JsonIgnore
를 붙이게 되면 해당 필드는 json으로 매핑하지 않기 때문에 해결이 되지만 view에서 필요한 경우 문제가 될 수 있습니다.
@Entity
public class EntityA {
@JsonBackReference
@ManyToOne
private EntityB entityB;
}
@Entity
public class EntityB {
@JsonManagedReference
@ManyToOne
private EntityA entityA;
}
😊위의 경우
@JsonBackReference
붙은 곳에서는 역으로 참조를 안하기에 해결이 됩니다.
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class EntityA {
@ManyToOne
private EntityB entityB;
}
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class EntityB {
@ManyToOne
private EntityA entityA;
}
😎위 어노테이션을 사용하면 객체 식별자를 기반으로 직렬화/역직렬화를 수행하게 되는데 이 방법을 사용하게 되면 식별자를 기준으로 객체 참조를 처리하기 때문에 무한 참조 문제를 해결할 수 있습니다.
🥳DTO로 필요한 것만 반환하면 순환참조 문제를 해결 할 수 있습니다.
비록 코드량은 늘어나게 되지만 불필요한 데이터를 보내지 않아도 되지 않기에 이 방법을 가장 추천합니다.