Video in progress

Senior 🌱 Spring

How do you do soft delete (deleted = true) in Spring Data JPA, and what are its hidden costs?

In Hibernate 6.4+ you use @SoftDelete, in older versions @SQLDelete + @SQLRestriction. After that you deal separately with unique constraints, indexes, related tables, native queries and ever-growing volume.

📖 Answer

From Hibernate 6.4 on:

@Entity
@SoftDelete(columnName = "deleted")
class Customer { ... }

repo.delete(c) now does UPDATE customer SET deleted = true, and all JPQL/Criteria queries automatically get a deleted = false filter. In older versions the same thing is done with @SQLDelete(sql = "update customer set deleted_at = now() where id = ?") and @SQLRestriction("deleted_at is null") (before 6.3 it was @Where instead of @SQLRestriction).

Hidden problems:

  • Unique constraint. If email is unique, a user can't sign up again with the same email as a deleted user. In PostgreSQL a partial index solves it:
    CREATE UNIQUE INDEX ux_customer_email ON customer(email) WHERE deleted = false;
    
  • Native SQL and reports don't know about the filter. You have to write it by hand in every native query, and if you forget, deleted data shows up.
  • Relationships. A customer was deleted, but what about their orders? You write the cascading soft delete yourself.
  • If you need to "see deleted records" (admin, restore), the automatic filter gets in the way: you need a separate native query or a separate view.
  • Volume. The table keeps growing; you need to add the deleted column to indexes or use a partial index.
  • Legal requirements. If deleting personal data is required (like GDPR), soft delete is not deletion.

So I first ask: what is soft delete actually for? If the goal is audit or restore, moving the deleted record to a separate archive table or a history table (Envers, trigger) is often the cleaner solution: the main table stays small and queries stay simple.