gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:17:04 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com