Tech/JPA

detached entity passed to persist 에러

소프 2021. 12. 1.
    public static Apple 잠금해제상태_스케줄_생성() {
        return Apple.builder()
            .id(1)
            .name("사과")          
            .build();
    }

테스트코드에서 Fixture로 Apple 엔티티를 생성할려구 했다.

 

@AllArgsConstructor
@NoArgsConstructor( access = AccessLevel.PROTECTED )
@Builder
@Entity
public class Apple {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    //...

엔티티 설정은 다음과 같다.

 

JpaRepository를 상속받아 save()메소드로 생성한 엔티티를 저장할려구 했는데

 

detached entity passed to persist 에러가 발생했다.

 

원인은 엔티티에 @GeneratedValue를 사용해서 자동생성하겠다고 선언을 했는데 

id를 직접 세팅 후 persist를 호출하면 JPA는 해당 객체가 detached 상태의 객체라 생각한다.

detached 객체는 이전에 한번 영속화 되었던 적이 있는 객체 (DB에 저장되어 있는 데이터를 JPA의 findById로 조회한 

 

참고

https://www.inflearn.com/questions/121326

 

영속성 공부하다가 궁금한게 생겼습니다 . - 인프런 | 질문 & 답변

class A  {   @GeneratedValue   @Id   private Long id;  } 일떄 아래 run 메서드에서  @Transactional @Component public class JpaRunn...

www.inflearn.com

 

댓글