Why am I getting the remote instance passed in for merge the first time I merge the object
I believe that the object I want to delete is a managed object. But, no matter why it is a merge and then deleting it, I get the following error:
remote instance passed to merge
Someone said on stackoverflow that merge should be ignored if it is a managed entity. So why isn't this ignored?
The way I want to remove is like this:
TrialUser mergedEntity = em.merge(tu);
em.remove(mergedEntity);
But these errors, but if I get rid of the first line, it works fine. But I want it differently because it is consistent with the rest of the code.
EDIT:
@PersistenceContext(unitName = "UnitName")
protected EntityManager entityManager;
@Table(name="TRIAL_USER")
@Id
private BigDecimal id;
@ManyToOne(cascade= {CascadeType.ALL }, fetch=FetchType.EAGER)
@JoinColumn(name="TRIAL_USER_CLASS_ID3")
private TrialUserElement trialUserElement3;
@ManyToOne(cascade= {CascadeType.ALL }, fetch=FetchType.EAGER)
@JoinColumn(name="TRIAL_USER_CLASS_ID1")
private TrialUserElement trialUserElement1;
@ManyToOne(cascade= {CascadeType.ALL }, fetch=FetchType.EAGER)
@JoinColumn(name="TRIAL_USER_CLASS_ID2")
private TrialUserElement trialUserElement2;
source to share
This error can occur when running some code in a transaction when you commit at the end of this method. When using spring in a method or class annotated with
@Transactional
This is because you first delete the object (without committing) and then try to update it.
this code throws an exception:
@Transactional
myethod(){
dao.delete(myObject);
myObject.setProperty("some value");
dao.save();
}
To avoid the error, you should not delete and then save in the same transaction.
source to share
This is a bit of a shot in the dark as I can't get your code running and these problems can get a little tricky. But rest assured that it should be good to merge and then delete. I suspect it might be related to your multiple related objects.
The moment a transaction is committed, the cascading of related objects is removed.
Even though the merge is overkill for your parent, I think the merge is cascading to the children that were deleted, hence the exception.
Try changing your cascading rules - put it back in CascadeType.MERGE (for all three) and see if you all get an exception. Or change to CascadeType.DELETE, this will prevent the required merge from cascading.
source to share