I know that invoking merge() on a detached object should be just fine. Even if you explicitly invoke detach() operation to detach an object after the merge() operation and modify it is just fine. However it doesn't work on related entities if you explicitly invoke detach() operation on them and modify. And that's what I want to understand why. It throws "org.hibernate.PersistentObjectException: detached entity passed to persist"
Here's an example:
Could anyone enlighten me on this? AFAIK, merge should work on detached objects but seeing the result, it seems to me that it's not the merge() operation that is being cascaded on the related entities but the persist() operation.
I just now got some clarifications on "Detached" state of Object concept...
As you said,
How the detach() method can trigger this exception???...
And this exception usually occurs when you "persist()" a "Transient" object (newly instantiated) with having "Primary Key" field set with a value and Entity Manager assumes that this object is in Detached state...
Ensure that there is an associating member variable "a" in the class B...
SCJP 6 [SCJP - Old is Gold]
posted 9 years ago
Oops sorry, it's supposed to be mappedBy="parent" and not mappedBy="a".
The line this.getEm().detach( b ) doesn't throw the exception immediately. The exception is thrown after the transaction ends when the method has ended. Removing that line will make it work just fine.
What I don't understand is why it throws an exception when it is clearly legal to invoke merge() operation on a detached entity. The update() function demonstrates that it is legal to invoke merge() operation on detached or explicitly detached entity. update2() completely contradicts this and that's what I want to understand why.