I receive following error when I save the object using Hibernate
object references an unsaved transient instance - save the transient instance before flushing
I receive following error when I save the object using Hibernate
object references an unsaved transient instance - save the transient instance before flushing
Simple way of solving this issue is save the both entity. first save the child entity and then save the parent entity. Because parent entity is depend on child entity for the foreign key value.
Below simple exam of one to one relationship
In my case it was caused by not having
CascadeType
on the@ManyToOne
side of the bidirectional relationship. To be more precise, I hadCascadeType.ALL
on@OneToMany
side and did not have it on@ManyToOne
. AddingCascadeType.ALL
to@ManyToOne
resolved the issue. One-to-many side:Many-to-one side (caused the problem)
Many-to-one (fixed by adding
CascadeType.PERSIST
)beside all other good answers, this could happen if you use
merge
to persist an object and accidentally forget to use merged reference of the object in the parent class. consider the following exampleIn this case, you merge
A
but forget to use merged object ofA
. to solve the problem you must rewrite the code like this.Or, if you want to use minimal "powers" (e.g. if you don't want a cascade delete) to achieve what you want, use
If you're using Spring Data JPA then addition
@Transactional
annotation to your service implementation would solve the issue.