下面的代码将如何在 JPA 内部执行?

How will the below code get executed internally in JPA?

entityManager.getTransaction.begin();

Employee emp = new Employee();

emp.setName("Abc");

emp.setCity("Pune");

entityManager.persist(emp);

emp.setName("Xyz");

entityManager.getTransaction.commit();

我知道它会更新名称,但它在内部如何运作?比如当执行 entityManager.persist(emp); 和执行 entityManager.getTransaction.commit(); 时,流程是什么,对数据库有什么影响?

当您调用 entityManager.persist(emp); 时,实体并未物理持久保存在数据库中。它由 Persistence Provider 从那时起进行管理。

当您调用 entityManager.getTransaction.commit(); 时,这是生成持久化实体的实际物理插入的地方。

您可以通过调用 entityManager.flush() 告诉持久性提供者在提交事务之前执行插入到数据库中,这基本上使上下文与数据库同步。您必须记住,这不会提交事务,因此数据仍然可以回滚。