MyEntity e = new MyEntity();
// scenario 1// tran startsem.persist(e);e.setSomeField(someValue);// tran ends, and the row for someField is updated in the database
// scenario 2// tran startse = new MyEntity();em.merge(e);e.setSomeField(anotherValue);// tran ends but the row for someField is not updated in the database// (you made the changes *after* merging)
// scenario 3// tran startse = new MyEntity();MyEntity e2 = em.merge(e);e2.setSomeField(anotherValue);// tran ends and the row for someField is updated// (the changes were made to e2, not e)
{AnyEntity newEntity;AnyEntity nonAttachedEntity;AnyEntity attachedEntity;
// Create a new entity and persist itnewEntity = new AnyEntity();em.persist(newEntity);
// Save 1 to the database at next flushnewEntity.setValue(1);
// Create a new entity with the same Id than the persisted one.AnyEntity nonAttachedEntity = new AnyEntity();nonAttachedEntity.setId(newEntity.getId());
// Save 2 to the database at next flush instead of 1!!!nonAttachedEntity.setValue(2);attachedEntity = em.merge(nonAttachedEntity);
// This condition returns true// merge has found the already attached object (newEntity) and returns it.if(attachedEntity==newEntity) {System.out.print("They are the same object!");}
// Set 3 to valueattachedEntity.setValue(3);// Really, now both are the same object. Prints 3System.out.println(newEntity.getValue());
// Modify the un attached object has no effect to the entity manager// nor to the other objectsnonAttachedEntity.setValue(42);}
//MERGE: passedEntity remains unmanaged, but newEntity will be managedEntity newEntity = em.merge(passedEntity);
//PERSIST: passedEntity will be managed after thisem.persist(passedEntity);