프로그래밍/Java

[spring boot JPA] object references an unsaved transient instance - save the transient instance before flushing 오류 원인

소행성왕자 2023. 8. 25. 15:10

"object references an unsaved transient instance - save the transient instance before flushing" 오류는 Hibernate 또는 JPA에서 발생하는 오류로, 영속성 컨텍스트에 저장되지 않은(transient) 엔티티를 다른 엔티티가 참조하고 있을 때 발생합니다. 이 경우, 영속성 컨텍스트는 참조한 엔티티를 올바르게 관리하지 못하므로 오류가 발생합니다.

이 오류를 해결하기 위해 다음을 확인하십시오:

연관 엔티티 저장: 먼저 연관 엔티티(Team)를 저장한 후, 메인 엔티티(Members)에 연관 엔티티를 설정하세요. 영속성 컨텍스트는 참조된 엔티티가 영속 상태로 저장되어 있어야 합니다.

원본

Members members = new Members();
members.setUserName("길동");

Team team = new Team();
team.setName("The Avengers");

members.setTeam(team);

membersRepository.save(members);

수정후

Team team = new Team();
team.setName("The Avengers");
teamRepository.save(team); // 팀을 저장

Members members = new Members();
members.setUserName("길동");
members.setTeam(team); // 이제 연관 엔티티를 설정
membersRepository.save(members);


Cascade 설정 확인: 연관 관계에 대한 Cascade 설정이 올바르게 구성되어 있는지 확인하십시오. Cascade 설정을 통해 부모 엔티티를 저장할 때 연관된 자식 엔티티도 자동으로 저장할 수 있습니다.

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "team_id")
private Team team;


트랜잭션 관리: 트랜잭션을 올바르게 관리하고 있는지 확인하십시오. 트랜잭션을 시작하고 커밋/롤백하는 코드가 필요합니다.

@Transactional
public void saveMembersWithTeam() {
    Team team = new Team();
    team.setName("The Avengers");
    teamRepository.save(team);

    Members members = new Members();
    members.setUserName("길동");
    members.setTeam(team);
    membersRepository.save(members);
}


위의 조치를 취하면 "object references an unsaved transient instance" 오류를 해결할 수 있어야 합니다. 이 오류는 연관 엔티티를 영속성 컨텍스트에 저장하고, 올바르게 설정 및 관리하는 데 관련된 문제를 나타냅니다.