JPA - Refreshing an Entity Instance

[Updated: Dec 1, 2017, Created: Nov 21, 2017]

By invoking EntityManager#refresh(entity), we can synchronize the current persistence context to the underlying database. In other words, by invoking this method, we can reload the state of a managed entity instance from the database. The existing state of the entity instance is overwritten.

The refresh operation is cascaded to entities referenced by this entity if the attribute cascade=REFRESH or cascade=ALL are used (check out cascading tutorial).

If this method is invoked on the entity which is new (not yet persisted), detached, or removed , the IllegalArgumentException is thrown.

Example

The Entity

@Entity
public class Employee {
  @Id
  @GeneratedValue
  private Integer id;
  private String name;
  private String department;

  public Employee() {
  }

  public Employee(String name, String department) {
      this.name = name;
      this.department = department;
  }
    .............
}

Persisting and refreshing

public class ExampleMain {

  public static void main(String[] args) {
      EntityManagerFactory emf =
              Persistence.createEntityManagerFactory("example-unit");
      try {
          persistEntities(emf);
          displayEntities(emf);
      } finally {
          emf.close();
      }
  }

  private static Employee persistEntities(EntityManagerFactory emf) {
      System.out.println("-- persisting employee --");
      EntityManager em = emf.createEntityManager();
      Employee employee = new Employee("Sara Dorsey", "Admin");
      em.getTransaction().begin();
      em.persist(employee);
      em.getTransaction().commit();
      em.close();

      print("Employee persisted", employee);
      return employee;
  }

  private static void displayEntities(EntityManagerFactory emf) {
      //loading all entities
      EntityManager em = emf.createEntityManager();
      Query query = em.createQuery("Select e from Employee e");
      List<Employee> list = (List<Employee>) query.getResultList();
      for (Employee employee : list) {
          //sending to ui for display
          displayEntity(employee);
          print("refreshing employee", employee);
          //now refreshing entity before doing something with it
          em.refresh(employee);
          print("after refreshing employee", employee);
      }
  }

  private static void displayEntity(Employee employee) {
      System.out.println("-- displaying employee --");
      System.out.println(employee);
      employee.setDepartment("Sales");
      print("employee modified in displayEntity()", employee);
  }


  private static void print(String msg, Object... objects) {
      System.out.printf("%s: %s%n", msg, Arrays.asList(objects));
  }
}

Output

-- persisting employee --
Employee persisted: [Employee{id=1, name='Sara Dorsey', department='Admin'}]
-- displaying employee --
Employee{id=1, name='Sara Dorsey', department='Admin'}
employee modified in displayEntity(): [Employee{id=1, name='Sara Dorsey', department='Sales'}]
refreshing employee: [Employee{id=1, name='Sara Dorsey', department='Sales'}]
after refreshing employee: [Employee{id=1, name='Sara Dorsey', department='Admin'}]

Example Project

Dependencies and Technologies Used :

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.10.Final: The core O/RM functionality as provided by Hibernate.
  • JDK 1.8
  • Maven 3.3.9

EntityManager#refresh() Example Select All Download
  • entity-refresh-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • META-INF

See Also