Video in progress

How do you do soft delete in Hibernate 6?

Since Hibernate 6.4 there is @SoftDelete: remove() updates a flag column instead of running a DELETE, and the filter is added to queries automatically. The older way is @SQLDelete + @SQLRestriction (@Where up to Hibernate 6.3).

📖 Answer

The new way:

@Entity
@SoftDelete(columnName = "deleted")
public class Customer {
    @Id @GeneratedValue
    private Long id;
    private String name;
}

em.remove(customer) now runs update customer set deleted = true where id = ?, and select c from Customer c automatically gets where deleted = false added. @SoftDelete manages a boolean column; the option to store the deletion time was added in later versions, so check your version.

If you need more control, do it by hand:

@Entity
@SQLDelete(sql = "update customer set deleted_at = now() where id = ?")
@SQLRestriction("deleted_at is null")
public class Customer { ... }

Here deleted_at also records when it was deleted.

Problems you run into in practice:

  • Unique constraint. The deleted ali@mail.uz is still in the database, so a new signup with the same email fails. On PostgreSQL a partial index solves it: create unique index ... on customer(email) where deleted_at is null.
  • Associations. If an active Order points to a deleted Customer, order.getCustomer() can throw EntityNotFoundException in some cases, because the filter doesn't see it.
  • Native SQL and reports don't know about the filter, so you have to write the condition by hand.
  • Table growth. If you don't add deleted_at is null to your indexes, queries slow down.

Sometimes, instead of soft delete, moving deleted rows to a separate archive table turns out simpler.