Video in progress
How do you do soft delete in Hibernate, and where does it cause problems?
Hibernate 6.4+ has the @SoftDelete annotation; before that the @SQLDelete and @SQLRestriction pair was used. Problems: unique indexes, native queries, cascades and the table growing without bound.
📖 Answer
Since Hibernate 6.4 the cleanest way is:
@Entity
@SoftDelete(columnName = "deleted")
public class Customer { ... }
remove() now does an UPDATE, and the condition deleted = false is added to all queries automatically. In older versions we did it by hand: @SQLDelete(sql = "update customer set deleted_at = now() where id = ?") and @Where for the filter (renamed to @SQLRestriction in 6.3).
Now the tricky parts.
Unique constraints. If email is unique, you cannot create a new customer with the same email as a deleted one. On PostgreSQL a partial index solves it: create unique index on customer(email) where deleted = false.
Native SQL and reports. @SoftDelete only affects the SQL that Hibernate generates. The analytics team's queries will keep counting deleted rows.
Associations. If an order points to a deleted customer through @ManyToOne, what should happen when you load it? That is a question to settle with the business.
Growth. Nothing is ever removed, so tables and indexes keep growing. I usually add a job that moves deleted rows to an archive table after some time.
Sometimes you don't need soft delete at all: if it is for auditing, Envers or a separate history table is the cleaner solution.
Sign up to mark studied questions and save your progress.