EntityManager em = Persistence.createEntityManagerFactory("example-unit").createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); // Retrieve entity from database MyEntity entity = em.find(MyEntity.class, 1L); // Modify entity in another part of application entity.setName("New name"); // Refresh entity in EntityManager em.refresh(entity); transaction.commit(); em.close();
// Create entity manager EntityManager em = Persistence.createEntityManagerFactory("example-unit").createEntityManager(); // Retrieve entity from database MyEntity entity = em.find(MyEntity.class, 1L); // Start thread 1 new Thread(() -> { // Modify entity entity.setName("Thread 1 name"); // Wait for 5 seconds try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // Refresh entity to ensure latest state em.refresh(entity); }).start(); // Start thread 2 new Thread(() -> { // Modify entity entity.setName("Thread 2 name"); // Wait for 3 seconds try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // Refresh entity to ensure latest state em.refresh(entity); }).start(); // Close entity manager em.close();The javax.persistence.EntityManager class is part of the Java Persistence API (JPA) and is included in the javax.persistence package library.