I’ve faced with this error many times when trying to save an object to the db using hibernate.
The main reason is caused by the default behavior of hibernate to the relations between objects.
If you do not specify the cascade type in the hbm.xml file, then hibernate acts like it is a null relation which means
the related object is already in the db. For example, assume there are two concrete classes called Person and Address; Person has a one to many one directional
association with the Address..
public class Person {
private String name;
private String surname;
private Address address;
…
…
…
}
public class Address {
private String street;
private int zipcode;
private String city;
…
…
…
}
The association in the Person.hbm.xml will look like;
one-to-many name=”address” class=”Address”
Everything seems fine however when we try to save a person instance the error following exception will likely to occur.
//Assume you have the ready person instance at this point
Session session = sessions.openSession();
Transaction tx = session.beginTransaction();
session.save(Person);
tx.commit();
session.close();
object references an unsaved transient instance – save
the transient instance before flushing
The transient instance the error mentioned is the address of the person because hibernate thinks that the address is already in the db since you are not referring to a persistent address object.
In order to overcome this error, you can either define a cascade for the relation like “save-update, all etc”. or save the address before saving the person.
1) one-to-many name=”address” class=”Address” cascade=”all-delete-orphan”
After changing to this, the same code will work.
2) If you do not want to change the xml, you can try this;
//Assume you have the ready person instance at this point
Session session = sessions.openSession();
Transaction tx = session.beginTransaction();
session.save(person.getAddress());
session.save(person);
tx.commit();
session.close();
