Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 308
Tushar Ahirrao Avatar asked Feb 20 '10 16:02

Tushar Ahirrao


People also ask

What is transient instance in Java?

1. Transient State: A New instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate: UserDetail user = new UserDetail(); user.setUserName("Dinesh Rajput"); // user is in a transient state.

Can an object in hibernate go from persistence state to transient state?

No, it's not possible. Transient object are objects with no reference in database. Persistent and detached on the other hand have representation in database (are persisted). Detached object is persisted, but for this object hibernate session is closed.

What is transient instance state in hibernate?

Hibernate defines and supports the following object states: Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session . It has no persistent representation in the database and no identifier value has been assigned.


2 Answers

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.

like image 89
Bozho Avatar answered Oct 01 '22 07:10

Bozho


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;
}
like image 37
McDonald Noland Avatar answered Oct 01 '22 08:10

McDonald Noland