Home > Mobile >  Hibernate Print Before and After Update
Hibernate Print Before and After Update

Time:01-02

I have this little issue I'm struggling with. I have a very similar Update query. What I want is to see the result before and after the Update. The update is done successfully but there is some issue in the printing. I believe there is some small thing I'm missing.

The code:

EntityManagerFactory factory = Persistence.createEntityManagerFactory("exercise");
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();

Scanner scanner = new Scanner(System.in);
String address = scanner.nextLine();
String lastName = scanner.nextLine();

Employee employee = findEmployee(entityManager, lastName);
printEmployeeData(employee); // Prints Employee data before the Update

entityManager.createQuery(
                "UPDATE Employee e"  
                        " SET e.address = :address"  
                        " WHERE e.lastName = :name")
        .setParameter("address", address)
        .setParameter("name", lastName)
        .executeUpdate(); // Successfully updated the Employee

System.out.printf("%n%n");
employee = findEmployee(entityManager, lastName);
printEmployeeData(employee); // Prints the same output as the one before the Update

entityManager.getTransaction().commit();
entityManager.close();


private static Employee findEmployee(EntityManager entityManager, String lastName) {
    return entityManager.createQuery("SELECT e FROM Employee e"  
                    " WHERE lastName = :lastName", Employee.class)
            .setParameter("lastName", lastName)
            .getSingleResult();
}

I think the problem might be somewhere in the entityManager?

CodePudding user response:

You need to call entityManager.refresh(employee) to fetch the results of the UPDATE query from the database.

The entity manager has no way to know which entities in memory were affected by the UPDATE.

  • Related