A different object with the same identifier value was already associated with the session

By | 2020년 12월 23일
Table of Contents

A different object with the same identifier value was already associated with the session

원인

하나의 세션(런타임) 동안 동일한 PK 의 엔터티가 두개 이상 존재할 때 발생한다.

일반적으로는 동일한 PK 의 엔터티를 2회 이상 조회해도 a == b 가 되어 문제되지 않지만, 코드가 복잡해지면 a != b 인 상태가 되고 예외를 발생시킨다.

해결책

가장 좋은 방법은 하나의 엔터티는 한번만 조회하는것이 가장 좋다.

하지만 그렇게 하지 못할 경우 간단한 방법은 아래와 같이 compareTo() 를 구현해 주는 것이다.

하지만 이 방법은 JPA 에서 보장하던 영속성을 스스로 깨는 방법이고, a, b 두개의 엔터티에 서로 다른 업데이트가 발생했을 때, 어떤 내용이 저장되는지를 예측할 수 없어, 지양되어야 할 방법입니다.

@Setter
@Getter
@NoArgsConstructor
@Entity
@Table(name = "tbl_ipgo_master", catalog = "db_storage")
public class IpgoMaster implements Comparable<IpgoMaster> {

    // ......

    @Override
    public int compareTo(IpgoMaster o) {
        if(this == o) return 0;
        return this.getIpgoId().compareTo(o.getIpgoId());
    }
}

답글 남기기