Home > Enterprise >  Does invoking javax.persistence.TypedQuery.getResultList cause a transaction to be committed?
Does invoking javax.persistence.TypedQuery.getResultList cause a transaction to be committed?

Time:06-08

In a Java 1.8 SE environment using Hibernate 5 as my JPA provider, I have the following code:

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService");
    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();

    Employee employee = new Employee(1);
    employee.setName("Bob");
    employee.setSalary(100000);
    
    em.persist(employee);
    
    System.out.println("em"   em.find(Employee.class, 1));          
    System.out.println("em all Employees"   em.createQuery("SELECT e from Employee e", Employee.class).getResultList());
    
    em.clear();
    
    em.getTransaction().commit();

    System.out.println("em after commit "   em.find(Employee.class, 1));            
    System.out.println("em after commit all Employees"   em.createQuery("SELECT e from Employee e", Employee.class).getResultList());

    em.close();
    emf.close();

I was expecting this output because of calling em.clear() before the commit:

emEmployee(id=1, name=Bob, salary=100000.0)
em after commit null
em after commit all Employees[]

but got:

emEmployee(id=1, name=Bob, salary=100000.0)
em all Employees[Employee(id=1, name=Bob, salary=100000.0)]
em after commit Employee(id=1, name=Bob, salary=100000.0)
em after commit all Employees[Employee(id=1, name=Bob, salary=100000.0)]

If I comment out the line with the getResultList() call just before em.clear(), I get the expected output. Why don't I get the output I expected when calling getResultList?

CodePudding user response:

SQL logging will show inserts/updates before it executes the query. It is up to the provider how to handle when to flush statements to the database, but this can be configured by specifying the FlushModeType on the Query, on the EntityManager or the persistence unit with provider specific properties (see hibernate and EclipseLink)

  • Related