Data management is a fundamental component in software development, especially when handling records that need removal from active use. Instead of permanently deleting records (a method known as “hard delete”), many applications use a technique called “soft delete.” The “soft delete” approach is a widely used solution that marks records as inactive without permanently removing them, enabling easy data recovery and historical tracking.
Currently, unlike Spring Data JPA and Hibernate, Spring Data R2DBC does not offer built-in annotations for automatically handling soft-delete. As a result, developers resort to the use of custom repository implementations or queries to achieve similar functionality.
In this article, we’ll examine soft delete, its benefits, and how to implement it in a Spring WebFlux application with R2DBC.
What is Soft Delete
Soft delete is a data management method where records are flagged as inactive or “deleted” without being removed from the database. Typically, this involves adding a field to the entity, like deleted (a boolean) or deletedDate (a timestamp), to indicate that a record is no longer active. Instead of permanently deleting data, a soft delete marks the record as logically deleted, hiding it from standard queries while preserving it for potential recovery or auditing.
Benefits of Soft Delete
- Data Recovery: Soft delete allows for easy restoration of data. If a record is accidentally deleted, it can be quickly “undeleted” by resetting the flag, ensuring that no data is permanently lost.
- Historical Data: Soft delete provides an audit trail. Organisations often need to keep historical data for compliance or reporting purposes, and soft delete enables this without crowding active data.
- Data Integrity: In systems with complex relationships, permanently deleting a record can cause broken links and data inconsistencies. Soft delete addresses this by keeping related data intact while marking the deleted records as inactive.
- Security and Compliance: Regulations often require data to be retained for specific periods. Soft delete enables developers to meet these compliance needs without making the data available to regular users.
How to implement Soft Delete with Spring Reactive and R2DBC
If you’re interested in implementing this yourself, I’ve prepared a starter code — a simple blog application with basic CRUD endpoints and unit test cases. You can access the starter code from my GitHub repository using this link. So, let's get right to it.
Step 1: Add a Field to Mark Records as Deleted
To implement this, add a field in your entity class to represent the deletion status. A more effective approach is to create an abstract class (AbstractSoftDeletableEntity), define the deletion status field within it, and have your entity class extend this abstract class. This field could either be a boolean (deleted) indicating whether the record is deleted or a timestamp (deletedDate) to specify when it was deleted. I recommend using a timestamp, as it provides the added detail of when the deletion took place:
public abstract class AbstractSoftDeletableEntity extends AbstractAuditingEntity { | |
@JsonIgnore | |
@Column("deleted_date") | |
public Instant deletedDate; | |
} |
Step 2: Modify the entity class to extend the abstract class
Modifying the entity class to extend the AbstractSoftDeletableEntity creates a level of abstraction and separation of concern, thus adhering to the Single Responsibility Principle of object-oriented design.
@Table("posts") | |
public class Post extends AbstractSoftDeletableEntity { | |
@Id | |
private Long id; | |
@Column("title") | |
public String title; | |
@Column("body") | |
public String body; | |
public Post() {} | |
public Post(String title, String body) { | |
this.title = title; | |
this.body = body; | |
} | |
public Long getId() { | |
return id; | |
} | |
} |
Step 3: Create a Generic Custom Repository Extending the SimpleR2dbcRepository
Many resources on implementing soft delete recommend using a custom repository for each entity, which can be cumbersome and hard to manage when an application has numerous entities. A better approach is to use a generic repository interface while providing custom implementations for the basic methods such as counts, deleteById, deleteAll, findById, and others.
public class SoftDeleteRepositoryImpl<T extends AbstractSoftDeletableEntity, ID> implements SoftDeleteRepository<T, ID> { | |
private final R2dbcEntityOperations entityOperations; | |
private final R2dbcConverter converter; | |
public SoftDeleteRepositoryImpl(R2dbcEntityOperations entityOperations, R2dbcConverter converter) { | |
this.entityOperations = entityOperations; | |
this.converter = converter; | |
} | |
@NonNull | |
@Override | |
public Mono<Long> count(Class<T> entityClass) { | |
return this.entityOperations.count(Query.query(where(getDeletedFieldProperty().getName()).isNull()), entityClass); | |
} | |
@NonNull | |
@Override | |
public Mono<Boolean> existsById(@NonNull ID id, Class<T> entityClass) { | |
Assert.notNull(id, "Id must not be null"); | |
var criteria = Criteria.where(getIdProperty(entityClass).getName()).is(id) | |
.and(getDeletedFieldProperty().getName()).isNull(); | |
return this.entityOperations.exists(Query.query(criteria), entityClass); | |
} | |
@NonNull | |
@Override | |
public Mono<T> findById(@NonNull ID id, Class<T> entityClass) { | |
var criteria = Criteria.where(getIdProperty(entityClass).getName()).is(id) | |
.and(getDeletedFieldProperty().getName()).isNull(); | |
return this.entityOperations.selectOne(Query.query(criteria), entityClass); | |
} | |
@NonNull | |
@Override | |
public Flux<T> findAll(Class<T> entityClass) { | |
return this.entityOperations.select(Query.query(where(getDeletedFieldProperty().getName()).isNull()), entityClass); | |
} | |
@NonNull | |
@Override | |
public Flux<T> findAllById(@NonNull Iterable<ID> iterable, Class<T> entityClass) { | |
Assert.notNull(iterable, "The iterable of Id's must not be null"); | |
return findAllById(Flux.fromIterable(iterable), entityClass); | |
} | |
@NonNull | |
@Override | |
public Flux<T> findAllById(@NonNull Publisher<ID> idPublisher, Class<T> entityClass) { | |
Assert.notNull(idPublisher, "The Id Publisher must not be null"); | |
return Flux.from(idPublisher).buffer().filter(ids -> !ids.isEmpty()).concatMap(ids -> { | |
if (ids.isEmpty()) { | |
return Flux.empty(); | |
} | |
String idProperty = getIdProperty(entityClass).getName(); | |
var criteria = Criteria.where(idProperty).in(ids) | |
.and(getDeletedFieldProperty().getName()).isNull(); | |
return this.entityOperations.select(Query.query(criteria), entityClass); | |
}); | |
} | |
@NonNull | |
@Override | |
public Flux<T> findAll(@NonNull Sort sort, Class<T> entityClass) { | |
Assert.notNull(sort, "Sort must not be null"); | |
var query = Query.query(where(getDeletedFieldProperty().getName()).isNull()); | |
return this.entityOperations.select(query.sort(sort), entityClass); | |
} | |
@NonNull | |
@Override | |
@Transactional | |
public Mono<Void> softDeleteAll(Class<T> entityClass) { | |
return this.entityOperations.update(Query.empty(), | |
Update.update(getDeletedFieldProperty().getName(), Instant.now()), | |
entityClass | |
).then(); | |
} | |
@NonNull | |
@Override | |
@Transactional | |
public Mono<Void> softDeleteAllById(@NonNull Iterable<? extends ID> ids, Class<T> entityClass) { | |
Assert.notNull(ids, "The iterable of Id's must not be null"); | |
List<? extends ID> idsList = Streamable.of(ids).toList(); | |
var query = Query.query(where(getIdProperty(entityClass).getName()).in(idsList)); | |
var update = Update.update(getDeletedFieldProperty().getName(), Instant.now()); | |
return this.entityOperations.update(query, update, entityClass).then(); | |
} | |
@NonNull | |
@Override | |
@Transactional | |
public Mono<Void> softDeleteById(@NonNull ID id, Class<T> entityClass) { | |
Assert.notNull(id, "id must not be null"); | |
var query = Query.query(where(getIdProperty(entityClass).getName()).is(id)); | |
var update = Update.update(getDeletedFieldProperty().getName(), Instant.now()); | |
return this.entityOperations.update(query, update, entityClass).then(); | |
} | |
private RelationalPersistentProperty getDeletedFieldProperty() { | |
return this.converter | |
.getMappingContext() | |
.getRequiredPersistentEntity(AbstractSoftDeletableEntity.class) | |
.getRequiredPersistentProperty("deletedDate"); | |
} | |
private RelationalPersistentProperty getIdProperty(Class<T> entityClass) { | |
return this.converter | |
.getMappingContext() | |
.getRequiredPersistentEntity(entityClass) // | |
.getRequiredIdProperty(); | |
} | |
} |
In the snippet above, I have the SoftDeleteRepositoryImpl implementing the SoftDeleteRepository interface, which provides another abstraction layer by listing abstract methods enhanced for soft delete operation.
public interface SoftDeleteRepository<T, ID> { | |
@NonNull | |
Mono<Long> count(Class<T> entityClass); | |
@NonNull | |
Mono<Boolean> existsById(@NonNull ID id, Class<T> entityClass); | |
@NonNull | |
Mono<T> findById(@NonNull ID id, Class<T> entityClass); | |
@NonNull | |
Flux<T> findAll(Class<T> entityClass); | |
@NonNull | |
Flux<T> findAllById(@NonNull Iterable<ID> iterable, Class<T> entityClass); | |
@NonNull | |
Flux<T> findAllById(@NonNull Publisher<ID> idPublisher, Class<T> entityClass); | |
@NonNull | |
Flux<T> findAll(@NonNull Sort sort, Class<T> entityClass); | |
@NonNull | |
@Transactional | |
Mono<Void> softDeleteAll(Class<T> entityClass); | |
@NonNull | |
Mono<Void> softDeleteAllById(@NonNull Iterable<? extends ID> ids, Class<T> entityClass); | |
@NonNull | |
@Transactional | |
Mono<Void> softDeleteById(@NonNull ID id, Class<T> entityClass); | |
} |
Step 4: Modifying the Entity Repository to extend the Custom Repository Interface
Finally, modify the main repository interface by extending the SoftDeleteRepository and providing the entity class name and the id data type as the generic type arguments. It also provides a default implementation for the findById, findAll, deleteById, and deleteAll methods to make use of the soft delete custom implementations defined in the SoftDeleteRepository interface.
@Repository | |
public interface PostRepository extends SoftDeleteRepository<Post, Long>, ReactiveCrudRepository<Post, Long> { | |
@NonNull | |
default Mono<Post> findById(@NonNull Long id) { | |
return findById(id, Post.class); | |
} | |
@NonNull | |
default Flux<Post> findAll() { | |
return findAll(Post.class); | |
} | |
@NonNull | |
@Transactional | |
default Mono<Void> deleteById(@NonNull Long id) { | |
return softDeleteById(id, Post.class); | |
} | |
@NonNull | |
@Transactional | |
default Mono<Void> deleteAll() { | |
return softDeleteAll(Post.class); | |
} | |
} |
Step 5: Implement Soft Delete in the Service Layer
Once you’ve completed the steps above, you’re all set. No further implementation is needed at the domain service layer. Notably, both the controller and unit test cases also required no modifications.
To fetch all records (including deleted records) or deleted records, you can make use of query methods as shown in the snippet below:
@Repository | |
public interface PostRepository extends ReactiveCrudRepository<Post, Long>, SoftDeleteRepository<Post, Long> { | |
Flux<PostWithDeleteStamp> findByDeletedDateIsNotNull(); | |
@Query("select * FROM posts") | |
Flux<PostWithDeleteStamp> findAllEntries(); | |
// delete (hard-delete) all posts from the database | |
@Query("delete from posts") | |
Mono<Void> flush(); | |
// all other methods... | |
} |
Conclusion
Soft delete is an effective and flexible method for managing data without permanently deleting it, making it ideal for applications needing data recovery, compliance, or historical data tracking. In this guide, we discussed what soft delete is, its benefits, and how it can be implemented in a Spring WebFlux application with R2DBC.
You can find the complete source code on GitHub
Top comments (0)