Search code examples
javajpatransactionspersistenceentitymanager

entity manager implicit transaction commit


Let's take into consideration the following code snippet:

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);
     }
}

please note that this example refers to Transaction Scoped,container managed Entity Manager.

from 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.

I really cannot understand how does the entity manager knows the method is closed and implicitly commits the transaction...
Am I missing something here ? Should we commit the transaction explicitly ?


Solution

  • Yes you are missing something:

    Your service isn't just an instance of EmployeeServiceImpl but of a proxy class which wraps EmployeeServiceImpl and every public method in it. And when your method exits the wrapping method takes over and commits the transaction. If you debug your application and set a breakpoint in assignEmployeeToProject() you can see very easily what is happening in the stacktrace.