https://github.com/scottmarlow/hibernate-orm/tree/refreshEntityNotFoundException contains the following test case that expects a EntityNotFoundException to be thrown from refresh if the entity is no longer in the database.
{code} @Test public void testEntityNotFoundException() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand("Lacoste"); w.setModel("Minimic"); w.setSerial("0324"); em.persist(w); Wallet wallet = em.find( Wallet.class, w.getSerial() ); em.createNativeQuery("delete from Wallet").executeUpdate(); try { em.refresh(wallet); } catch (EntityNotFoundException enfe) { // success if (em.getTransaction() != null) { em.getTransaction().rollback(); } em.close(); return; }
try { em.getTransaction().commit(); fail("Should have raised an EntityNotFoundException"); } catch (PersistenceException pe) { } finally { em.close(); } } {code}
The following code change works around the issue: {code} @Test public void testEntityNotFoundException() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand("Lacoste"); w.setModel("Minimic"); w.setSerial("0324"); em.persist(w); /******** End the txn and start a new one, to work around the issue. */ em.getTransaction().commit(); em.getTransaction().begin(); Wallet wallet = em.find( Wallet.class, w.getSerial() ); em.createNativeQuery("delete from Wallet").executeUpdate(); try { em.refresh(wallet); } catch (EntityNotFoundException enfe) { // success if (em.getTransaction() != null) { em.getTransaction().rollback(); } em.close(); return; }
try { em.getTransaction().commit(); fail("Should have raised an EntityNotFoundException"); } catch (PersistenceException pe) { } finally { em.close(); } }
{code}
Javadoc description of EntityManager.refresh(Object) {code} /** * Refresh the state of the instance from the database, * overwriting changes made to the entity, if any. * @param entity * @throws IllegalArgumentException if the instance is not * an entity or the entity is not managed * @throws TransactionRequiredException if there is no * transaction when invoked on a container-managed * entity manager that is of type * PersistenceContextType.TRANSACTION. * @throws EntityNotFoundException if the entity no longer * exists in the database */ public void refresh(Object entity); {code}
|