본문 바로가기

Java/오류

[오류 / JPA] dentifier of (엔티티) an instance of Entity was altered from A to B

 

identifier of an instance of (Entity) was altered

[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of (엔티티) was altered from   (  A  )    to   (  B  )    with root cause

 

본질적으로는 JPA 영속성 관련 문제인데, 

(JPA에서는 객체들을 우선 영속성 컨텍스트에 등록(flush) 후에 db에 반영한다(commit) )

영속성 컨텍스트에 등록된 엔티티의 식별자(id)를 변경하려고 하면 발행할 수 있는 오류이다.

id값만을 변경할 수는 없고, 변경하고 싶다면 기존 엔티티를 삭제하고 새로운 엔티티를 추가하는 방식으로 해야한다.

 


 

saveAll () 메소드로 데이터를 저장하려고 했더니 발생했고,

해당 테이블의 id가 복합키로 설정되어 있는데 이에 대한 클래스 파일을 생성해주지 않아서 발생한 오류였다.

아래의 예시처럼 @IdClass 를 사용했는데, 

@IdClass(UserIdAndEamil.class)  =>  UserIdAndEamil 클래스 파일이 없었다.

@Entity
@Table(name = "users")
@IdClass(UserIdAndEmail.class)
public class User {

    @Id
    @Column(name = "user_id")
    private Long id;

    @Id
    @Column(name = "user_email")
    private String email;
    
}

 

아래처럼 생성해주고 변수명만 맞춰주면 된다.

( UserIdAndEamil )

@Data
public class UserIdAndEmail implements Serializable {

    private Long id;
    private String email;

}

이렇게 PK 두개를 묶어서 하나의 엔티티 식별자로 만들어줘야 한다.