[ERROR] A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance:

gnoesnooj·2024년 3월 20일
0

상황

스프링 실행 중, 다음과 같은 오류 발생
@Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.

원인

public class Game {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String replayUrl;

    @ElementCollection(fetch = FetchType.LAZY)
    private List<String> highlights; // 회원 id,

    private int gender;

    private Long manager;

    private LocalDate startDate; // 경기일

    private int time; // 경기 시간대, 0~24

    private boolean isOver;

    private int playerNumber;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn
    private Team teamA;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn
    private Team teamB;

    @OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Player> playersA = new ArrayList<>();

    @OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Player> playersB = new ArrayList<>();
    
	public void inputData(GameDataInputDto dto) {
        this.teamA = dto.getTeamA();
        this.teamB = dto.getTeamB();
        this.playersA = dto.getPlayersA();
        this.playersB = dto.getPlayersB();
    }
 }

이런 식으로 어떤 Entity와 일대다 관계 매핑을 해놓은 상태에서,

inputData() 를 이와 같이 매핑된 컬렉션 데이터에 대해 새로운 값을 할당하는 것 처럼 처리를 하면 이와 같은 에러가 발생한다.

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance:

쉽게 말해 새로운 컬렉션 객체가 할당되면서 엔티티와의 참조가 끊어지기 때문에 이와 같은 오류가 발생한다..

해결

참조가 끊어지지 않게 새로운 객체를 할당하는 것이 아닌, 기존 객체에 참여하도록 코드를 바꿔준다.

	public void inputData(GameDataInputDto dto) {
        this.teamA = dto.getTeamA();
        this.teamB = dto.getTeamB();
        for (Player p : dto.getPlayersA()) {
            this.playersA.add(p);
            p.mapGame(this);
        }
        for (Player p : dto.getPlayersB()) {
            this.playersB.add(p);
            p.mapGame(this);
        }
    }
profile
누구나 믿을 수 있는 개발자가 되자 !

1개의 댓글

comment-user-thumbnail
2024년 3월 26일

와 정말 많은 도움이 되었습니다.!! 감사합니다.^__^!!!

답글 달기