java - 实体管理器隐式事务提交

标签 java jpa transactions persistence entitymanager

让我们考虑以下代码片段:

public class EmployeeServiceImpl implements EmployeeService
{
    @PersistenceContext(unitName="EmployeeService")

    EntityManager em;

     public void assignEmployeeToProject(int empId, int projectId)
     {
        Project project = em.find(Project.class, projectId);
        Employee employee = em.find(Employee.class, empId);
        project.getEmployees().add(employee);
        employee.getProjects().add(project);
     }
}

请注意,此示例指的是事务范围、容器管理的实体管理器。

来自javacodegeeks :

By the end of 2nd line in the method both project and employee instance are managed. At the end of the method call, the transaction is committed and the managed instances of person and employee get persisted. Another thing to keep in mind is that when the transaction is over, the Persistence Context goes away.

我真的无法理解实体管理器如何知道该方法已关闭并隐式提交事务...
我在这里错过了什么吗? 我们应该显式提交事务吗?

最佳答案

是的,你错过了一些东西:

您的服务不仅仅是 EmployeeServiceImpl 的实例,而是包装 EmployeeServiceImpl 及其中每个公共(public)方法的代理类。当您的方法退出时,包装方法将接管并提交事务。如果您调试应用程序并在 assignEmployeeToProject() 中设置断点,您可以非常轻松地看到堆栈跟踪中发生的情况。

关于java - 实体管理器隐式事务提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31699205/

相关文章:

java - 从命令提示符运行简单的 JBDC 程序

java - 应用于属性的 @Inject 会生成 NullPointerException

mysql - @SQLResultSetMapping+Joins 在多个实体上的不同结果 |日本PA

postgresql - 关于Postgres track_commit_timestamp (pg_xact_commit_timestamp)的问题

Java 字体使用项目错误

java - 如何在 Mac 上用 Java 运行命令 'pdflatex'

java - 如何映射这个复合主键?

java - JPA 和 DTO,创建 DTO 的最佳方式?

Spring、Hibernate 事务。加入 A 中创建的线程 B 中的事务。可能吗?

entity-framework - Entity Framework 4.1 批量更新