Different Ways to Delete JPA Entity Objects from Database

In this article, we will discuss various ways to delete objects from the database.
Existing entity objects can be deleted from the database either explicitly by invoking the remove() method or implicitly as a result of a cascade operation.
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial
This article covers the following topics:
  1. Explicit Remove
  2. Cascading Remove
  3. Orphan Removal
  4. DELETE Queries

1. Explicit Remove

In order to delete an object from the database, it has to first be retrieved (no matter which way), and then in an active transaction, it can be deleted using the remove() method:
private static void removeEntity() {
    EntityManager entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
    entityManager.getTransaction().begin();

    Student student = entityManager.find(Student.class, 1);
    System.out.println("student id :: " + student.getId());
    System.out.println("student firstname :: " + student.getFirstName());
    System.out.println("student lastname :: " + student.getLastName());
    System.out.println("student email :: " + student.getEmail());
    entityManager.remove(student);
    entityManager.getTransaction().commit();
    entityManager.close();
}
The entity object is physically deleted from the database when the transaction is committed. Embedded objects that are contained in the entity object are also deleted. If the transaction is rolled back and not committed the object is not deleted.
An IllegalArgumentException is thrown by remove if the argument is not an instance of an entity class or if it is a detached entity. A TransactionRequiredException is thrown if there is no active transaction when remove is called because operations that modify the database require an active transaction.

2. Cascading Remove

Marking a reference field with CascadeType.REMOVE (or CascadeType.ALL, which includes REMOVE) indicates that remove operations should be cascaded automatically to entity objects that are referenced by that field (multiple entity objects can be referenced by a collection field):

Instructor.java

@Entity
@Table(name="instructor")
public class Instructor {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id")
 private int id;
 
 @Column(name="first_name")
 private String firstName;
 
 @Column(name="last_name")
 private String lastName;

 @Column(name="email")
 private String email;
 
 @OneToOne(cascade=CascadeType.ALL)
 @JoinColumn(name="instructor_detail_id")
 private InstructorDetail instructorDetail;
 
 @OneToMany(mappedBy="instructor",
      cascade= {CascadeType.REMOVE})
 private List<Course> courses;

        // getters and setters
}

Course.java

@Entity
@Table(name="course")
public class Course {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id")
 private int id;
 
 @Column(name="title")
 private String title;
 
 @ManyToOne(cascade=CascadeType.ALL)
 @JoinColumn(name="instructor_id")
 private Instructor instructor;
        // getters and setters methods
}
In the example above, the Instructor entity class contains a courses field that references an instance of Course, which is another entity class. Due to the CascadeType.REMOVE setting, when an Instructor instance is removed the operation is automatically cascaded to the referenced Course instances, which are then automatically removed as well. 
Cascading may continue recursively when applicable (e.g. to entity objects that the Course object references, if any).

3. Orphan Removal

JPA 2 supports an additional and more aggressive remove cascading mode which can be specified using the orphanRemoval element of the @OneToOne and @OneToMany annotations:
@Entity
class Employee {
     :
    @OneToOne(orphanRemoval=true)
    private Address address;
     :
}
When an Employee entity object is removed the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.
Orphan removal can also be set for collection and map fields. For example:
@Entity
class Employee {
     :
    @OneToMany(orphanRemoval=true)
    private List<Address> addresses;
     :
}
In this case, the removal of an Address object from the collection leads to the automatic removal of that object from the database.

4. DELETE Queries

DELETE queries provide an alternative way for removing entity objects from the database. Deleting objects using a DELETE query may be useful especially when many entity objects have to be deleted in one operation.

Delete All Queries

The simplest form of a DELETE query removes all the instances of a specified entity class (including instances of subclasses) from the database.
For example, the following three equivalent queries delete all the Country instances:
DELETE FROM Country       // no variable
DELETE FROM Country c     // an optional variable
DELETE FROM Country AS c  // AS + an optional variable
DELETE queries are executed using the executeUpdate method:
  int deletedCount = em.createQuery("DELETE FROM Country").executeUpdate();
A TransactionRequiredException is thrown if no transaction is active.
On success - the executeUpdate method returns the number of objects that have been deleted by the query.
Refer complete JPA CRUD operations example at JPA CRUD Example
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial

Related Articles

Comments