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
I believe this might be just repeat answer, but just to clarify, I got this on a
@OneToOne
mapping as well as a@OneToMany
. In both cases, it was the fact that theChild
object I was adding to theParent
wasn't saved in the database yet. So when I added theChild
to theParent
, then saved theParent
, Hibernate would toss the"object references an unsaved transient instance - save the transient instance before flushing"
message when saving the Parent.Adding in the
cascade = {CascadeType.ALL}
on theParent's
reference to theChild
solved the problem in both cases. This saved theChild
and theParent
.Sorry for any repeat answers, just wanted to further clarify for folks.
This isn't the only reason for the error. I encountered it just now for a typo error in my coding, which I believe, set a value of an entity which was already saved.
I spotted the error by finding exactly which variable caused the error (in this case
String xid
). I used acatch
around the whole block of code that saved the entity and printed the traces.Don't use
Cascade.All
until you really have to.Role
andPermission
have bidirectionalmanyToMany
relation. Then the following code would work finewhile if the object is just a "new" one, then it would throw the same error.
There is another possibility that can cause this error in hibernate. You may set an unsaved reference of your object
A
to an attached entityB
and want to persist objectC
. Even in this case, you will get the aforementioned error.Case 1: I was getting this exception when I was trying to create a parent and saving that parent reference to its child and then some other DELETE/UPDATE query(JPQL). So I just flush() the newly created entity after creating parent and after creating child using same parent reference. It Worked for me.
Case 2:
Parent class
Child Class:
In the above case where parent(Reference) and child(ReferenceAdditionalDetails) having OneToOne relationship and when you try to create Reference entity and then its child(ReferenceAdditionalDetails), it will give you the same exception. So to avoid the exception you have to set null for child class and then create the parent.(Sample Code)
One possible cause of the error is the inexistence of the setting of the value of the parent entity ; for example for a department-employees relationship you have to write this in order to fix the error :