title: How can I reliably unit test updates of a JPA entity in a unit test
body: <p>I have this test setup where I'm using spring, derby and JPA and I want to test whether updates work.</p>
  
  <p>I can't really do this in the standard way, that is. Create an entity object, persist, find object again, change some field in the object, persist again, do a find to see whether it has changed.</p>
  
  <p>The problem with that approach is that I don't get a new instance of the entity. It is always the same. So I can't really tell if update works correctly because I am always changing the same object, so any change is reflected prematurely.</p>
  
  <p>If I make a change to some object without merging it with the persistencecontext, and then try to do a find on that object, the change is already present in the find as it is always working with the same object.</p>
  
  <p>Is there any way I can lose the context and do a real test that updating is working correctly?</p>
  
  <p>Here is my current code:</p>
  
  <pre><code>@Test
  public void canUpdate() {
  
      JsonTestEntity entity1 = new JsonTestEntity();
      JsonTestEntity entity2 = new JsonTestEntity();
  
      String message = "OmegaCV1";
      String message2 = "OmegaCV2";
  
      entity1.setMessage(message);
      entity2.setMessage(message2);
  
      em.persist(entity1);
      em.persist(entity2);
  
      em.flush();
  
      JsonTestEntity jsonTestEntity = em.find(JsonTestEntity.class, entity2.getId());
  
      assertNotNull("Could not find persisted entity", jsonTestEntity);
      assertEquals("Was not same entity", message2, jsonTestEntity.getMessage());
  
      String changeMessage = "Changed message";
      jsonTestEntity.setMessage(changeMessage);
  
      JsonTestEntity unChangedEntity = em.find(JsonTestEntity.class, entity2.getId());
  
      assertEquals("Message was prematurely changed", message2, unChangedEntity.getMessage());
      em.merge(jsonTestEntity);
  
      JsonTestEntity changedEntity = em.find(JsonTestEntity.class, entity2.getId());
      assertEquals("Message was not changed", changeMessage, changedEntity.getMessage());
  }
  </code></pre>