Solution:
You must add cascade="all"
(if using xml) or cascade=CascadeType.ALL
(in case using annotations) on your collection mapping.
This occurs since you have a collection in your entity, and that collection has one or more items which are not present in the database. By secluding the above options you say hibernate to save them to the database at the time saving their parent.
I conceive this might be only repeat answer, however only to clarify, I obtained this on a @OneToOne
mapping as well as a @OneToMany
. In both instances, it was the fact that the Child
object I was including to the Parent
wasn't saved in the database yet. Therefore at the time I included 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 at the time saving the Parent.
including in the cascade = {CascadeType.ALL}
on the Parent's
reference to the Child
solved the problem in both instances. This saved the Child
and the Parent
.
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "performancelog_id")
public PerformanceLog getPerformanceLog() {
return performanceLog;
}
This occurs at the time saving an object at the time Hibernate thinks it requires to save an object that is associated with the one you are saving.
I had this issue and did not want to save changes to the referenced object. Therefore I wanted the cascade type to be NONE.
The trick is to make sure that ID and VERSION in the referenced object is place so that Hibernate does not figure out that the referenced object is a new object that requires saving. This performed for me.
Look through all of the relationships in the class you are saving to perform out the associated objects (and the associated objects of the associated objects) and make sure the ID and VERSION is place in all objects of the object tree.
Or, in case you want to employ minimal "powers" (for example in case you don't want a cascade delete) to achieve what you want, use
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
...
@Cascade({CascadeType.SAVE_UPDATE})
private Set<Child> children;
In my instances it was happened by not having CascadeType
on the @ManyToOne
side of the bidirectional relationship. To be more precise, I had CascadeType.ALL
on @OneToMany
side and did not have it on @ManyToOne
. Including CascadeType.ALL
to @ManyToOne
resolved the problem. One-to-many side:
@OneToMany(cascade = CascadeType.ALL, mappedBy="globalConfig", orphanRemoval = true)
private Set<GlobalConfigScope>gcScopeSet;
Many-to-one side (caused the problem)
@ManyToOne
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;
Many-to-one (fixed by including CascadeType.PERSIST
)
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;