Site icon codippa

How to soft delete a record in Hibernate or JPA / Soft deletion of Entities in Hibernate or JPA

Soft Delete !!! What the heck ?

Soft delete means that the record is not removed from the database table but a flag is set to a value which indicates that this record should not be fetched while fetching the records from this table. The flag shall be a value of a column in the table itself.

For example, there is a deleted column in a table which has a value of false for a record which is newly inserted in the table but when a record is deleted, it is not removed from the table but the value of deleted column for this record is set to true. Now when fetching records from the table, only those records should be fetched which have a false in deleted column.

Soft Delete !!! Why ?

Soft delete has many practical scenarios. Suppose you have an application from which a user accidentally deleted some records through the UI of application or let’s say you want to give a rollback feature in your application. How will you retrieve accidentally deleted records or rollback delete action when there is nothing to retrieve or rollback !!! Soft delete is to the rescue. With soft delete you just update the flag of a record and the record is back to life.

Soft Delete !!! How ?

Now comes the main point, how do I implement soft delete. Before moving forward, let’s define an entity whose records we will be soft deleting. Entity class follows :

  @Entity
  @Table(name="users")
  public class User {
     @Id
     long id;
     @Column(name="username")
     String userName;
     @Column(name="country")
     String country;
     @Column(name="state")
     String state;
     @Column(name="age")
     int age;
    /* Getter and Setter methods follow */

 }

Now, in order to implement soft delete, first add a column to the database table and a corresponding field in the entity which will decide whether the entity record is marked as deleted or not. Updated entity is as follows :

  @Entity
  @Table(name="users")
  public class User {
     @Id
     long id;
     @Column(name="username")
     String userName;
     @Column(name="country")
     String country;
     @Column(name="state")
     String state;
     @Column(name="age")
     int age;
     /* 
     * Column that will hold delete decision
     */
     @Column(name="deleted")
     String deleteFlag;
    /* Getter and Setter methods follow */

 }

There may be two methods by which you are playing with entities in your application, that is,fetching, inserting or deleting entities. They are :

Exit mobile version