1. Overview
While working with databases in our applications, we usually have to deal with deleting records that are no longer useful. However, due to business or regulatory requirements, such as data recovery, audit tracing, or referential integrity purposes, we may need to hide these records instead of deleting them.
In this tutorial, we’ll take a look at the @SoftDelete annotation from Hibernate and learn how to implement it.
2. Understanding the @SoftDelete Annotation
The @SoftDelete annotation provides a convenient mechanism to mark any record as active or deleted. It has three different configuration parts:
- The strategy configures whether to track the rows that are active or which are deleted. We can configure it by setting the strategy as either ACTIVE or DELETED
- The indicator column identifies which column will be used to track the rows. If there are no specified columns, the strategy uses the default columns (active or deleted).
- The converter defines how the indicator column is set in the database. The domain type is a boolean value indicating whether the record is active or deleted. However, by implementing AttributeConverter, we can set the relational type to any type as defined by the converter. The available converters are NumericBooleanConverter, YesNoConverter, and TrueFalseConverter.
3. Implementing @SoftDelete
Let’s look at a few examples of how we can use @SoftDelete with different configurations.
3.1. Models
Let’s define an entity class SoftDeletePerson which we annotate with @SoftDelete. We don’t provide any additional configuration, and the annotation takes all the default values, such as a strategy of DELETED, a deleted indicator column, and storage as a boolean type.
The @SoftDelete annotation supports the @ElementCollection, which we’ve defined with a configured strategy as ACTIVE, a default indicator column, and storage as ‘Y’ or ‘N’ using the YesNoConverter:
@SoftDelete
public class SoftDeletePerson {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "Emails", joinColumns = @JoinColumn(name = "id"))
@Column(name = "emailId")
@SoftDelete(strategy = SoftDeleteType.ACTIVE,converter = YesNoConverter.class)
private List<String> emailIds;
// standard getters and setters
}
3.2. Data Setup
Let’s create a couple of database entries for the SoftDeletePerson entity and see how Hibernate saves them in the database:
@BeforeEach
public void setup() {
session = sessionFactory.openSession();
session.beginTransaction();
SoftDeletePerson person1 = new SoftDeletePerson();
person1.setName("Person1");
List<String> emailIds = new ArrayList<>();
emailIds.add("id1@dummy.com");
emailIds.add("id2@dummy.com");
person1.setEmailIds(emailIds);
SoftDeletePerson person2 = new SoftDeletePerson();
person2.setName("Person2");
List<String> emailIdsPerson2 = new ArrayList<>();
emailIdsPerson2.add("person2Id1@dummy.com");
emailIdsPerson2.add("person2Id2@dummy.com");
person2.setEmailIds(emailIdsPerson2);
session.save(person1);
session.save(person2);
session.getTransaction()
.commit();
assertNotNull(person1.getName());
assertNotNull(person2.getName());
System.out.println(person1);
System.out.println(person2);
}
In the test case above, we’ve persisted two SoftDeletePerson entities and printed the same to visualize what is persisted in the database. The output below shows that Hibernate saves the SoftDeletePerson with the deleted column set to false. Additionally, the collection emailIds has the active column set with the value ‘Y’:
3.3. Testing
In the previous step, we persisted a few rows in the database. Now, let’s see how @SoftDelete handles the deletion of records:
@Test
void whenDeletingUsingSoftDelete_ThenEntityAndCollectionAreDeleted() {
session.beginTransaction();
person1 = session.createQuery("from SoftDeletePerson where name='Person1'", SoftDeletePerson.class)
.getSingleResult();
person2 = session.createQuery("from SoftDeletePerson where name='Person2'", SoftDeletePerson.class)
.getSingleResult();
assertNotNull(person1);
assertNotNull(person2);
session.delete(person2);
List<String> emailIds = person1.getEmailIds();
emailIds.remove(0);
person1.setEmailIds(emailIds);
session.save(person1);
session.getTransaction()
.commit();
List<SoftDeletePerson> activeRows = session.createQuery("from SoftDeletePerson")
.list();
List<SoftDeletePerson> deletedRows = session.createNamedQuery("getDeletedPerson", SoftDeletePerson.class)
.getResultList();
session.close();
assertNotNull(person1.getName());
System.out.println("-------------Active Rows-----------");
activeRows.forEach(row -> System.out.println(row));
System.out.println("-------------Deleted Rows-----------");
deletedRows.forEach(row -> System.out.println(row));
}
First, we fetched the existing rows from the database. Next, we deleted one of the entities while for the other, we updated emailIds.
Then, when we delete one of the SoftDeletePerson entities, Hibernate sets deleted=true. Similarly, when we remove one of the email ids, Hibernate sets the previous rows to active=’N’, and inserts a new row with active=’Y’.
Finally, when we fetch the active and deleted rows, we can see the expected result:
4. Conclusion
In this article, we explored the implementation of the @SoftDelete annotation in Hibernate. The default configuration is with the DELETED strategy and stored as a boolean value in the database column deleted.
We also took a look at how the @ElementCollection is supported by this annotation. Finally, we verified the results with the test cases for the different configurations.
As always, the source code for all the examples can be found over on GitHub.