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
You should include
cascade="all"
(if using xml) orcascade=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 get this error when i use
but it works with no problem when I use
For the sake of completeness: A
with message
will also occur when you try to persist / merge an entity with a reference to another entity which happens to be detached.
I also faced the same situation. By setting following annotation above the property made it solve the exception prompted.
The Exception I faced.
To overcome, the annotation I used.
What made Hibernate throw the exception:
This exception is thrown at your console because the child object I attach to the parent object is not present in the database at that moment.
By providing
@OneToMany(cascade = {CascadeType.ALL})
, it tells Hibernate to save them to the database while saving the parent object.To add my 2 cents, I got this same issue when I m accidentally sending
null
as the ID. Below code depicts my scenario (and OP didn't mention any specific scenario).Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.
In some scenarios,
deptId
PKID is coming asnull
from calling method and I m getting the same error.So, watch for
null
values for PK IDThere are so many possibilities of this error some other possibilities are also on add page or edit page. In my case I was trying to save a object AdvanceSalary. The problem is that in edit the AdvanceSalary employee.employee_id is null Because on edit I was not set the employee.employee_id. I have make a hidden field and set it. my code working absolutely fine.