有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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.

我真的无法理解实体管理器如何知道方法已关闭并隐式提交事务
我是不是遗漏了什么? 我们应该显式地提交事务吗


共 (1) 个答案

  1. # 1 楼答案

    是的,你遗漏了一些东西:

    您的服务不仅是EmployeeServiceImpl的实例,而且是一个代理类的实例,它包装了EmployeeServiceImpl和其中的每个公共方法。当您的方法退出时,包装方法接管并提交事务。如果调试应用程序并在assignEmployeeToProject()中设置断点,则可以很容易地看到stacktrace中发生的情况