It turned out to be a transaction problem instead of cascade type. I was creating a new tnx after saving the scrMsgLine object. So it was becoming detached when i pass it to the new tnx. As a work around i read it from db in the begining of the new tnx. And i changed the cascade type to PERSIST. I am not sure if this is the right solution but for now it works for me...
How to use MERGE and PERSIST cascade types on many to one save or update operation?
-
11-10-2022 - |
سؤال
I have a mapping like below in one of my entities. When trying to save this entity, if scrMSgLine id is already set and the cascade type is PERSIST then i got the "org.hibernate.PersistentObjectException: detached entity passed to persist: ScrMsgLine" exception. If i change the cascade type to MERGE then record is saved succesfully.
If scrMSgLine id is null and cascade type is MERGE then i got the "object references an unsaved transient instance - save the transient instance before flushing" exception.
So which cascade type should i use, what am i doing wrong ?
@ManyToOne(cascade = {CascadeType.PERSIST})
@JoinColumn(name = "MSG_LINE_ID")
@Where(clause = "DELETED_AT IS NULL")
public ScrMsgLine getScrMsgLine() {
return scrMsgLine;
}
المحلول
نصائح أخرى
To avoid exceptions; use merge method to save your objects instead of persist and use CascadeType.ALL on ScrMsgLine.
As long as your relationships are set to CascadeType.ALL, you could always change your em.persist(exam); to em.merge(exam);. That would take care of persisting the new object, and it would also cascade the merge call to the ScrMsgLine.
And this Q&A may be more helpful.
I hope it helps.