Close

JPA - Removing Entities

[Last Updated: Dec 1, 2017]

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

If remove() is called on a detached entity, IllegalArgumentException will be thrown.

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 for cascade removal only, in that case other operations like persist() will not be cascaded. 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;
    @Temporal(TemporalType.TIMESTAMP)
    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();
    }
    .............
}
-- Persisting Employee entity --
-- Native queries --
'Select * from Employee'
[1, Maria Dorsey]
'Select * from Task'
[2, Refactoring, 2018-06-10 21:11:56.348]
-- removing entity --
Object: Employee{id=1, name='Maria Dorsey', tasks=[Task{id=2, name='Refactoring', startDate=2018-06-10 21:11:56.348}]}
-- 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.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

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

    See Also