Soft deletion is a widely used pattern. The general idea sounds trivial: instead of deleting entities, you just mark them as ‘deleted’ and filter them out from all SELECT queries. There are a few reasons to use soft deletion: audit, recoverability, or you need an option to be able to fake data deletion, keeping references to the deleted records.
In this article we will take a look into some details that stay uncovered by most of the articles about soft deletion implementation using Hibernate.
If you google ‘soft deletion hibernate’, you’ll most likely find tutorials by Eugen Paraschiv, Vlad Mihalcea or Thorben Janssen. They suggest to use Hibernate @SQLDelete and @Where annotations which let you automatically set the deleted flag and filter by it:
@SQLDelete takes a native SQL query that is executed whenever a Hibernate-managed entity gets deleted. @Where takes a condition and appends it to “select” queries automatically, allowing you to filter entities based on the deleted attribute automatically.