Soft deletion marks rows as deleted instead of removing them. The challenge is ensuring deleted rows never appear anywhere. Hibernate 6.4+: @SoftDelete @Entity @SoftDelete(columnName = "deleted") public class Customer { ... } - repository.delete(entity) issues UPDATE customer SET deleted = true. - All HQL/JPQL and criteria queries, entity loads and association fetches automatically exclude deleted rows — including joins and collection loading, which older approaches often missed. - Strategies include boolean flags and (in newer versions) timestamp-based deletion. Older approaches (pre-6.4) - @SQLDelete(sql = "UPDATE customer SET deleted = true WHERE id = ?") plus @SQLRestriction("deleted = false") (formerly @Where). @SQLRestriction applies to entity queries and collections, but care is needed with @ManyToOne associations and joins in custom queries. - Hibernate @Filter enabled per session: flexible (can be turned off for admin views) but easy to forget to enable. Where leaks still happen - Native queries (@Query(nativeQuery = true), JdbcTemplate, reporting tools) bypass Hibernate filters entirely: add the condition explicitly, or expose database views (active_customers) and query those. - JPQL joins to soft-deleted parents: decide whether children of deleted parents should be hidden too, and test it. - Aggregates and counts in custom SQL. - Unique constraints: a deleted row can block reusing an email or code. Use partial or filtered unique indexes (PostgreSQL: CREATE UNIQUE INDEX ... WHERE deleted = false). - Bulk JPQL deletes (DELETE FROM Customer c WHERE ...) may bypass entity-level soft-delete handling — use bulk updates instead. Defence in depth - PostgreSQL Row-Level Security policies that hide deleted rows from the application role, with a separate role for admin and restore functions. - Repository conventions: a base repository with explicit findActive... methods, and code review checks for native queries. Compliance and maintenance - Soft deletion is not erasure: for GDPR or India's DPDP Act requests, anonymise or hard-delete personal data, and purge old soft-deleted rows on a schedule. - Index the flag (or use partial indexes) so filtering stays cheap. Testing - Integration tests that delete an entity and verify it does not appear in list, detail, search, count, join and native-query endpoints.
Ravindra Wadile · · 0 likes