EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); // do some changes to the entity managed by the persistence context em.flush(); // execute a query to retrieve updated data from the database Query query = em.createQuery("SELECT e FROM Employee e WHERE e.salary > 50000"); Listresult = query.getResultList(); em.getTransaction().commit(); em.close();
// get the entity manager EntityManager em = Persistence.createEntityManagerFactory("myPersistenceUnit").createEntityManager(); // begin transaction em.getTransaction().begin(); // create a new entity Customer customer = new Customer("John", "Doe"); em.persist(customer); // flush changes to the database em.flush(); // commit transaction em.getTransaction().commit(); // close entity manager em.close();In this example, we create a new Customer entity and call the flush() method to ensure that it is persisted to the database before committing the transaction and closing the entity manager. The javax.persistence.EntityManager class is part of the Java Persistence API (JPA) library, which is included in the javax.persistence package.