NoTimeForDawdling

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

Error

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

Room_Energy 2021. 4. 17. 15:26

특정 Entity의 필드 값으로 List<String>를 들고 있었고, 해당 필드를 업데이트하려고 다음과 같은 에러가 발생했다!

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

 

매핑 관계는 다음과 같다.

    @OneToMany(mappedBy = "product", fetch = EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<File> fileList = new ArrayList<>();

 

그리고 문제의 업데이트 코드!

private void changeFileList(List<File> fileList) {
    this.fileList = fileList;
    for (File file : fileList) {
        file.setProduct(this);
    }
}

여기서 fileList는 외부에서 새로 만들어 넘겨준 값이다. 이렇게 새로 만들어준 값은 hibenate에서 관리하지 않아서 문제가 된다고 한다.

그래서 Collection에 새로운 값을 추가하거나 삭제할 때, 새 값을 할당하는 대신 수정해야 한다.

 

여기서는 기존에 있던 값을 지우고 새로운 값을 할당시켜줘야 한다. 즉, 해당 Collection의 내용(content)을 지우고 새로운 값을 넣어주면 된다.

 

수정한 코드

private void changeFileList(List<File> fileList) {
    if (!this.fileList.isEmpty()) {
        this.fileList.clear();
    }
    this.fileList.addAll(fileList);
    for (File file : fileList) {
        file.setProduct(this);
    }
}

에러 해결 완료~!

참고