Trouble Shooting

[Hibernate Error] TransientPropertyValueException : object references an unsaved transient instance

민뭉아치 2022. 3. 21. 13:54

1. 문제 상황

프로젝트에서 새로운 User을 생성하기 위해 회원가입을 진행하던 도중 다음과 같은 에러가 발생했다.

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - 
save the transient instance before flushing : dev.sma.basic.jpa.entity.UserEntity.residence -> 
dev.sma.basic.jpa.entity.AreaEntity

 

2. 원인

영속성에 의해 발생한 오류라고 한다.

FK로 사용되는 칼럼에 데이터가 없는 상태에서 데이터를 넣으면 발생한다.

현재  나의 프로젝트 기준으로 UserEntity가 AreaEntity와 @ManyToOne 관계를 가지고 있다.

AreaEntity로 생성된  'area' 테이블에 데이터를 넣지않고 User 데이터를 넣으려고 하니 FK인 area_id가 없기 때문에 발생했다.

 

3. 해결

@ManytoOne, @OnetoMany 어노테이션에 cascade 옵션을 추가해주면 된다.

cascade = CascadeType.ALL

cascade 옵션을 설정해줌으로써 parent에 데이터를 저장할 때 Child 데이터를 저장하도록  hibernate에 알려준다.

나의 프로젝트에서는 cacscade 옵션에 의해 User 데이터를 저장할 때 Area 데아터를 저장하도록 해준다.

@ManyToOne(
	targetEntity = AreaEntity.class,
	fetch = FetchType.LAZY,
	cascade = CascadeType.ALL
)
@JoinColumn(name = "area_id")
private AreaEntity residence;

 

 

4. 참고 

 

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

I receive following error when I save the object using Hibernate object references an unsaved transient instance - save the transient instance before flushing

stackoverflow.com

 

JPA 관련 Hibernate 에러: object references an unsaved transient instance - save the transient instance before flushing

에러 로그 TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing 원인 JPA 연관 관계 테스트 중에 발생했습니다. FK 로 사용되는..

bcp0109.tistory.com