JPA - Removing Entities

[Updated: Sep 8, 2017, Created: Sep 8, 2017]

Entities can be deleted from database by calling EntityManager#remove(anEntity) method. This operation must be invoked within a transaction.

Example

In the following example, we are going to use @OneToMany relationship with cascade = CascadeType.ALL, so the remove operation will be cascaded automatically to the referenced entity. We can also specify cascade = CascadeType.REMOVE to cascade removal, but other operations like persist() will not be cascaded in that case. We can also specify multiple cascade values e.g. cascade = {CascadeType.REMOVE, CascadeType.PERSIST}

Entities

@Entity
public class Employee {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  @OneToMany(cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
  private List<Task> tasks;
    .............
}
@Entity
public class Task {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  private Date startDate;
    .............
}

Persisting and Removing entity

public class ExampleMain {

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

          int id = persistEntity(emf);
          runNativeQueries(emf);
          removeEntity(emf, id);
          runNativeQueries(emf);

      } finally {
          emf.close();
      }
  }

  private static void removeEntity(EntityManagerFactory emf, int id) {
      EntityManager em = emf.createEntityManager();
      Employee employee = em.find(Employee.class, id);
      System.out.println("-- removing entity --");
      printObject(employee);

      em.getTransaction().begin();
      em.remove(employee);
      em.getTransaction().commit();
      em.close();
  }

  private static int persistEntity(EntityManagerFactory emf) {
      System.out.println("-- Persisting Employee entity --");
      EntityManager em = emf.createEntityManager();
      Task task = new Task();
      task.setName("Refactoring");
      task.setStartDate(new Date());

      Employee employee = new Employee();
      employee.setName("Maria Dorsey");
      employee.setTasks(Arrays.asList(task));

      em.getTransaction().begin();
      em.persist(employee);
      em.getTransaction().commit();
      em.close();
      return employee.getId();
  }
    .............
}

Output

-- Persisting Employee entity --
-- Native queries --
'Select * from Employee'
[1, Maria Dorsey]
'Select * from Task'
[2, Refactoring, 2017-09-08 21:11:18.734]
-- removing entity --
Object: Employee{id=1, name='Maria Dorsey', tasks=[Task{id=2, name='Refactoring', startDate=2017-09-08 21:11:18.734}]}
-- Native queries --
'Select * from Employee'
'Select * from Task'

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

Entity Removal Example Select All Download
  • entity-removal-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • META-INF

See Also