Hi,
I have the famous ERROR "object references an unsaved transient instance - save the transient instance before flushing" in a bidirectional ManyToOne-association, where I just call EntityManager.merge() on the One-side.
Yes, and I know, I have a) to have to mark both sides with cascade=CascadeType.MERGE and b) I have to declare on the MANY-side "mappedBy=...". So, I really did this.
What is going on, I just partly understand while debugging into Hibernate code. I noticed that Hibernate does the following:
- it calls newInstance on the class which is my root class which I gave EntityManager to merge.
- it copies this new instance into some cache, and the, before copying the values of the original object into it, it does "cascadeBeforeSave".
In this check process the error comes up: Hibernate does a check on the instance it created with newInstance. And of course detects, that this is transient. Then it throws.
So my problem is: I do not know what is the real reason for this behaviour. I can not image that this is a Hibernate bug (this would have been discovered a long time ago..), so it must result from my mappings.
I give you the main code points:
Code:
@Entity
public class CentralInstitution {
...
@ManyToOne(cascade=CascadeType.MERGE)
//@JoinColumn(name="USER_ID")
@JoinTable(name = "CENTRALINST_USER",
joinColumns = { @JoinColumn(name = "INSTITUT_ID") },
inverseJoinColumns = { @JoinColumn(name = "USER_ID") })
@org.hibernate.annotations.ForeignKey(name="FK_USER_CENTRALINST_ID")
private User responsible;
...
}
@Entity
public class User {
...
@OneToMany(mappedBy = "responsible", cascade = { CascadeType.MERGE } )
private Set<CentralInstitution> institutions = new HashSet<CentralInstitution>();
...
}
The association goes into a join table, because it is optional for a parallel super class of CentralInstitution.
If anyone has a idea what's going on: I need it URGENTLY!
Ciao, Carlo