How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error
You should include cascade="all"
(if using xml) or cascade=CascadeType.ALL
(if using annotations) on your collection mapping.
This happens because you have a collection in your entity, and that collection has one or more items which are not present in the database. By specifying the above options you tell hibernate to save them to the database when saving their parent.
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 the Child
object I was adding to the Parent
wasn't saved in the database yet. So when I added the Child
to the Parent
, then saved the Parent
, 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 the Parent's
reference to the Child
solved the problem in both cases. This saved the Child
and the Parent
.
Sorry for any repeat answers, just wanted to further clarify for folks.
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "performancelog_id")
public PerformanceLog getPerformanceLog() {
return performanceLog;
}
This happens when saving an object when Hibernate thinks it needs to save an object that is associated with the one you are saving.
I had this problem and did not want to save changes to the referenced object so I wanted the cascade type to be NONE.
The trick is to ensure that the ID and VERSION in the referenced object is set so that Hibernate does not think that the referenced object is a new object that needs saving. This worked for me.
Look through all of the relationships in the class you are saving to work out the associated objects (and the associated objects of the associated objects) and ensure that the ID and VERSION is set in all objects of the object tree.