@Test // Listing 4-14 public void shouldPersistACustomerAndThenRefreshIt() throws Exception { Customer03 customer = new Customer03("Antony", "Balla", "*****@*****.**"); Address03 address = new Address03("Ritherdon Rd", "London", "8QE", "UK"); customer.setAddress(address); // Persist the object tx.begin(); em.persist(customer); em.persist(address); tx.commit(); assertNotNull(customer.getId()); assertNotNull(address.getId()); customer = em.find(Customer03.class, customer.getId()); assertNotNull(customer); assertEquals(customer.getFirstName(), "Antony"); customer.setFirstName("New first name"); assertEquals(customer.getFirstName(), "New first name"); em.refresh(customer); assertEquals(customer.getFirstName(), "Antony"); }
@Test // Listing 4-12 public void shouldRemoveACustomer() throws Exception { Customer03 customer = new Customer03("Antony", "Balla", "*****@*****.**"); Address03 address = new Address03("Ritherdon Rd", "London", "8QE", "UK"); customer.setAddress(address); // Persist the object tx.begin(); em.persist(customer); em.persist(address); tx.commit(); assertNotNull(customer.getId()); assertNotNull(address.getId()); // Removes the object tx.begin(); em.remove(customer); em.remove(address); tx.commit(); assertEquals(customer.getFirstName(), "Antony"); assertEquals(address.getCity(), "London"); customer = em.find(Customer03.class, customer.getId()); assertNull(customer); address = em.find(Address03.class, address.getId()); assertNull(address); }
@Test public void shouldClearSetAndThenMergeACustomer() throws Exception { Customer03 customer = new Customer03("Antony", "Balla", "*****@*****.**"); // Persist the object tx.begin(); em.persist(customer); tx.commit(); assertTrue(em.contains(customer)); em.clear(); assertFalse(em.contains(customer)); tx.begin(); customer = em.merge(customer); customer.setFirstName("William"); tx.commit(); em.clear(); assertFalse(em.contains(customer)); customer = em.find(Customer03.class, customer.getId()); assertEquals(customer.getFirstName(), "William"); assertTrue(em.contains(customer)); }
@Test // Listing 4-18 public void shouldUpdateACustomer() throws Exception { Customer03 customer = new Customer03("Antony", "Balla", "*****@*****.**"); // Persist the object tx.begin(); em.persist(customer); assertNotNull(customer.getId()); assertEquals(customer.getFirstName(), "Antony"); customer.setFirstName("Williman"); assertEquals(customer.getFirstName(), "Williman"); tx.commit(); }