【问题标题】:How will the below code get executed internally in JPA?以下代码将如何在 JPA 内部执行?
【发布时间】:2017-09-26 13:47:12
【问题描述】:
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();被执行时,流程和对DB的影响是什么?

【问题讨论】:

    标签: java jpa transactions commit persist


    【解决方案1】:

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

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

    您可以通过调用entityManager.flush() 来告诉持久性提供程序在提交事务之前执行插入数据库,该entityManager.flush() 基本上将上下文与数据库同步。你必须记住,虽然这不会提交事务,所以数据仍然可以回滚。

    【讨论】:

    • 没错,我建议您阅读 JPA 实体生命周期,以及实体如何/何时同步到数据库。许多开发人员对 prequery-flush 感到困惑。
    猜你喜欢
    • 2021-01-18
    • 2012-10-31
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多