Question
What is the best way to implement soft delete functionality in Spring Data REST?
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private boolean deleted = false; // Soft delete flag
// Getters and Setters
}
Answer
Soft deleting is a common pattern in applications where you want to retain deleted records for audit or recovery purposes. In Spring Data REST, you can implement soft delete functionality by adding a 'deleted' flag to your entity and customizing the repository behavior to exclude those entities when querying.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByDeletedFalse(); // Fetch only non-deleted users
@Modifying
@Query("UPDATE User u SET u.deleted = true WHERE u.id = :id")
void softDelete(@Param("id") Long id);
}
Causes
- Lack of traditional DELETE operation required for maintaining data integrity.
- Need for record retention for regulatory compliance or audit trails.
- Desire to recover deleted records easily if needed.
Solutions
- Add a boolean field to your entity indicating whether the record is soft deleted.
- Override the default query methods in the Spring Data repository to filter out soft-deleted records.
- Implement custom methods for actual deletion functionality that updates the 'deleted' flag instead of removing the record from the database.
Common Mistakes
Mistake: Not indexing the 'deleted' column, leading to performance issues on large datasets.
Solution: Ensure that your database schema includes indexing on the 'deleted' column to optimize query performance.
Mistake: Excluding soft-deleted records in a way that causes inconsistent application behavior.
Solution: Always check the logic in your repository methods to ensure soft-deleted records are handled correctly.
Helpers
- Spring Data REST
- soft delete
- JPA soft delete
- Spring Data repository
- entity soft delete implementation
- Java persistence