EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); User user = entityManager.find(User.class, 1L); user.setName("Alice"); transaction.commit(); } catch (Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw e; } finally { entityManager.close(); }
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistenceUnit"); try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); User user = entityManager.find(User.class, 1L); user.setName("Alice"); transaction.commit(); } catch (Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw e; } }In this example, we use the try-with-resources statement to automatically close the EntityManager after the transaction is done. Package library: javax.persistence.