StackOverflowError : null
JPA에서 @OneToOne 양방향 매핑을 사용하고 에러가 났었다.
에러 내용은 StackOverflowError : null
왜떴나 싶었더니 Entity 연관관계를 맺을때 내가 실수한 부분이 몇개 있었다.
@OneToOne(mappedBy = "ParentEntity" , orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
private ChildEntity childEntity;
부모가 될 Entity 설정이고,
@OneToOne(fetch = FetchType.EAGER)
@JoinColum(name = "parentEntity_id")
private ParentEntity parentEntity;
자식관계의 엔티티를 이렇게 설정했다.
Service 설정은 다음과 같이 했다.
childEntity.setValue(request.getDto().getValue());
childRepository.save(childEntity);
parentEntity.setChildEntity(childEntity);
parentRepository.save(parentEntity);
Service 내용만 봐도.. 뭔가 이상함을 감지했다.
One To One으로 매핑되어있는데 세이브 자체를 이상하게 한것이다.
두 엔티티간에 일대일 관계에서 mappedBy 속성을 사용하는 쪽이 연관관계 주인이 되고,
@JoinColumn을 사용하는 쪽이 연관관계의 대상이 된다.
따라서 첫번째 엔티티 ParentEntity에서는 다음과 같이 수정한다.
@Entity
public class ParentEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idx;
@OneToOne(mappedBy = "parentEntity", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
private ChildEntity ChildEntity;
}
그러면 그다음인 연관관계의 대상이 될 ChildEntity를 수정해보자.
@Entity
public class ChildEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idx;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parentEntity_idx")
private ParentEntity parentEntity;
}
다음은 내가 사용하는 ParentResponseDto를 수정했다.
public class ParentResponseDto {
private Long idx;
private ChildDto child;
@Builder
public ParentResponseDto(ParentEntity entity) {
return ParentResponseDto.builder()
.idx(idx)
.ChildDto(new ChildDto(childDto));
.build();
}
}
이렇게 하고 실행을 해보니 정상적으로 해결!