entityManager.getTransaction.begin();
Employee emp = new Employee();
emp.setName("Abc");
emp.setCity("Pune");
entityManager.persist(emp);
emp.setName("Xyz");
entityManager.getTransaction.commit();
I know it'll update the name but how does it internally work? Like what will be the flow and what will be the effect on DB when entityManager.persist(emp);
is executed and entityManager.getTransaction.commit();
is executed?
When you call the entityManager.persist(emp);
, the entity is not physically persisted in the database. It is being managed from that point by the Persistence Provider.
When you call entityManager.getTransaction.commit();
, this is where the actual physical insert of the persisted entity is generated.
You can tell the persistent provider to perform the insert into the database before the transaction is commited by invoking the entityManager.flush()
which basically synchronizes the context with the database. You have to remember though that this will not commit the transaction, so that data could still be rolled back.