Skip to content

Instantly share code, notes, and snippets.

@tkfx
Created June 22, 2016 16:01
Show Gist options
  • Select an option

  • Save tkfx/1953955c59213872ebdb809cdbcae950 to your computer and use it in GitHub Desktop.

Select an option

Save tkfx/1953955c59213872ebdb809cdbcae950 to your computer and use it in GitHub Desktop.
// EntityManager and transaction 1
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
// EntityManager and transaction 2
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
// update 1
Author a = em.find(Author.class, 1L);
a.setFirstName("changed");
// update 2
Author a2 = em2.find(Author.class, 1L);
a2.setFirstName("changed");
// commit transaction 1
em.getTransaction().commit();
em.close();
// commit transaction 2
try {
em2.getTransaction().commit();
Assert.fail();
} catch (RollbackException e) {
Assert.assertTrue(e.getCause() instanceof OptimisticLockException);
log.info("2nd transaction failed with an OptimisticLockException");
}
em2.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment