Spring › Feature

Fixing JPA soft delete unique conflicts and building a trash bin

Avoid unique constraint violations on soft-deleted rows with PostgreSQL partial unique indexes and build an admin trash bin using Spring JDBC native SQL.

Fixing JPA soft delete unique conflicts and building a trash bin

Introducing soft delete in JPA immediately collides with standard UNIQUE constraints and hides deleted rows behind @SQLRestriction. This post explains how I solved both problems in PostgreSQL using partial unique indexes and a Spring JDBC admin trash bin that safely restores deleted records.

The problem: soft deletes collide with UNIQUE constraints

In production services, teams often mark rows with a deleted_at timestamp instead of running physical DELETE statements. Soft deletion protects against accidental data loss and preserves audit trails.

The moment you introduce soft delete, though, it collides head-on with a core RDBMS safeguard: the UNIQUE constraint.

flowchart TD
    subgraph Problem["Unique conflict on soft delete"]
        A["1. User signs up<br/>(email: test@example.com)"] --> B["2. User deletes account<br/>(UPDATE users SET deleted_at = NOW())"]
        B --> C["3. Re-register with same email<br/>(INSERT INTO users ...)"]
        C --> D["23505 unique_violation<br/>Soft-deleted row still occupies the unique index"]
    end

Why standard UNIQUE indexes break

A standard UNIQUE index doesn’t know what deleted_at IS NOT NULL means. As long as the row remains physically in the table, the index rejects any duplicate value.

In practice, this hits you in two common scenarios:

  1. Re-registering with the same email: A user deletes their account, which only sets deleted_at. Days later they sign up again with the same email and hit DataIntegrityViolationException (23505 unique_violation).
  2. Re-importing business records: In a legal precedent system with a composite unique key on (case_number, court_name, sentence_date), deleting a misentered judgment and re-importing it from a crawler fails with a unique violation.

Common workarounds and why they fail

ApproachHow it worksWhy it breaks
Include deleted_at in composite uniqueUNIQUE (email, deleted_at)In SQL, NULL != NULL. Active rows (deleted_at IS NULL) can still duplicate freely.
Dummy flag columnis_deleted (0 or id)Bloats the index, complicates queries, and still leaks business rules into schema hacks.
Hard deleteDELETE FROM ...Destroys audit history, breaks foreign key references, and makes recovery impossible.

Solution: PostgreSQL partial unique indexes

PostgreSQL supports partial indexes, which let you attach a WHERE predicate so only matching rows enter the index.

flowchart TD
    subgraph Table["users table"]
        R1["Row 1: test@example.com<br/>deleted_at: 2027-01-02"]
        R2["Row 2: test@example.com<br/>deleted_at: NULL"]
    end
    subgraph PartialIndex["Partial unique index (WHERE deleted_at IS NULL)"]
        Idx["test@example.com (Row 2 only)"]
    end
    R2 -.->|"Only active rows are indexed"| Idx

By scoping the unique index to WHERE deleted_at IS NULL, PostgreSQL enforces uniqueness strictly across active rows while ignoring soft-deleted rows.

1. Partial unique index DDL

1
2
3
4
5
6
7
8
9
-- Partial unique index for active user emails
CREATE UNIQUE INDEX uk_users_email_active
ON users (email)
WHERE deleted_at IS NULL;

-- Composite partial unique index for active judgments
CREATE UNIQUE INDEX uk_judgment_case_court_date_active
ON judgments (case_number, court_name, sentence_date)
WHERE deleted_at IS NULL;

Active rows can never share the same email or composite case identifier, while deleted rows stay archived in the same table without blocking re-registration or re-import.

2. Email suffixing and social account cleanup on withdrawal

Alongside partial indexes, you may also want to pseudonymize emails on account withdrawal (for privacy compliance) or free up linked OAuth identities immediately.

In my User entity, onDelete() clears linked SocialAccount rows (hard-deleting them via orphanRemoval = true) and appends a @deleted_yyyyMMdd-HHmmss suffix to the email:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// src/main/kotlin/com/example/server/user/domain/User.kt
package com.example.server.user.domain

import com.example.server.common.BaseEntity
import jakarta.persistence.*
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.UUID

@Entity
@Table(name = "users")
class User(
    @Id
    @GeneratedValue
    @Column(columnDefinition = "UUID", updatable = false)
    var id: UUID? = null,

    // Nullable because some OAuth providers do not return an email address
    @Column(unique = true, nullable = true)
    var email: String? = null,

    @Column(nullable = true)
    var nickname: String,

    @OneToMany(mappedBy = "user", cascade = [CascadeType.ALL], orphanRemoval = true)
    val socialAccounts: MutableSet<SocialAccount> = mutableSetOf(),
) : BaseEntity() {

    /**
     * Cleanup hook executed during [delete]:
     * 1. Hard-delete linked social accounts so the user can re-register with the same provider
     * 2. Append a timestamp suffix to the email to avoid unique constraint collisions
     */
    override fun onDelete(at: Instant) {
        socialAccounts.clear()
        email = email?.let { deletedEmail(it, at) }
    }

    companion object {
        private const val EMAIL_MAX_LENGTH = 255
        private val DELETED_SUFFIX_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss")
            .withZone(ZoneId.of("Asia/Seoul"))

        fun deletedEmail(email: String, at: Instant): String {
            val suffix = "@deleted_" + DELETED_SUFFIX_FORMAT.format(at)
            return email.take(EMAIL_MAX_LENGTH - suffix.length) + suffix
        }
    }
}

Designing BaseEntity with @SQLRestriction and onDelete

The whole point of soft delete is making sure normal queries never accidentally leak deleted rows. Relying on developers to remember WHERE deleted_at IS NULL in every repository method eventually causes a production bug.

Why @SQLRestriction instead of Hibernate 6 @SoftDelete

Hibernate 6 introduced @SoftDelete, which looks convenient at first glance, but it comes with sharp edges in real schemas:

  • Pairing @SoftDelete with @ManyToOne(fetch = FetchType.LAZY) often triggers proxy initialization errors or unexpected N+1 queries on joins.
  • @SoftDelete expects a boolean or custom converter column rather than a nullable timestamp (deleted_at) that doubles as an audit field.

In demo-backend-server, I placed @SQLRestriction("deleted_at IS NULL") on the root BaseEntity instead. Every subclass automatically excludes deleted rows from findById, list queries, and association loading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// src/main/kotlin/com/example/server/common/BaseEntity.kt
package com.example.server.common

import jakarta.persistence.Column
import jakarta.persistence.EntityListeners
import jakarta.persistence.MappedSuperclass
import jakarta.persistence.Version
import java.time.Instant
import org.hibernate.annotations.ColumnDefault
import org.hibernate.annotations.SQLRestriction
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener

/**
 * Shared audit, soft-delete, and optimistic-locking columns.
 *
 * Rows with a null [deletedAt] are active; non-null values mark the deletion time.
 * Always delete through [delete] and override [onDelete] for entity-specific cleanup.
 */
@MappedSuperclass
@SQLRestriction("deleted_at IS NULL")
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity(
    @CreatedDate
    @Column(updatable = false)
    var createdAt: Instant = Instant.now(),

    @LastModifiedDate
    var updatedAt: Instant = Instant.now(),

    @CreatedBy
    @Column(updatable = false)
    var createdUser: String? = null,

    @LastModifiedBy
    var updatedUser: String? = null,

    var deletedAt: Instant? = null,

    /**
     * Optimistic lock version to guard concurrent edits and restores.
     */
    @Version
    @ColumnDefault("0")
    var version: Long = 0,
) {
    val isDeleted: Boolean get() = deletedAt != null

    /**
     * Soft-deletes the entity after running the [onDelete] cleanup hook.
     */
    fun delete(at: Instant = Instant.now()) {
        onDelete(at)
        deletedAt = at
    }

    /**
     * Hook for subclasses to clean up associations before soft deletion.
     */
    protected open fun onDelete(at: Instant) {}
}

Guarding referential integrity before soft delete

If Entity A still holds a @ManyToOne foreign key to a soft-deleted Entity B, loading A will fail or return a broken proxy because @SQLRestriction hides B.

To prevent dangling references, AdminDeleteService checks active references before allowing a soft delete:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/main/kotlin/com/example/server/admin/application/AdminDeleteService.kt
package com.example.server.admin.application

import com.example.server.article.domain.ArticleJpaRepository
import com.example.server.common.BusinessException
import com.example.server.judgment.domain.JudgeJpaRepository
import com.example.server.judgment.domain.JudgmentErrorCode
import com.example.server.judgment.domain.JudgmentJpaRepository
import com.example.server.judgment.domain.JudgmentJudgeJpaRepository
import com.example.server.user.application.UserService
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional
class AdminDeleteService(
    private val userService: UserService,
    private val judgeRepository: JudgeJpaRepository,
    private val judgmentRepository: JudgmentJpaRepository,
    private val judgmentJudgeRepository: JudgmentJudgeJpaRepository,
    private val articleRepository: ArticleJpaRepository,
) {

    fun deleteJudge(id: Long) {
        val judge = judgeRepository.findByIdOrNull(id) ?: throw notFound("Judge")
        // Block deletion while the judge is referenced by an active judgment
        if (judgmentJudgeRepository.existsByJudgeId(id)) {
            throw BusinessException(JudgmentErrorCode.JUDGE_IN_USE)
        }
        judge.delete()
    }

    fun deleteJudgment(id: Long) {
        val judgment = judgmentRepository.findByIdOrNull(id) ?: throw notFound("Judgment")
        // Block deletion while an article still points to this judgment
        if (articleRepository.existsBySourceId(id)) {
            throw BusinessException(JudgmentErrorCode.JUDGMENT_HAS_ARTICLE)
        }
        judgment.delete() // onDelete() hard-deletes judge join rows
    }

    fun deleteArticle(id: Long) {
        val article = articleRepository.findByIdOrNull(id) ?: throw notFound("Article")
        article.delete()
    }
}

Admin trash bin architecture: bypassing JPA with native SQL

Once @SQLRestriction("deleted_at IS NULL") is active on BaseEntity, you hit an obvious dilemma: how does an admin trash bin query and restore rows where deleted_at IS NOT NULL?

Even if you write a JPQL query with WHERE deleted_at IS NOT NULL, Hibernate still appends AND deleted_at IS NULL automatically. The result set is always empty.

flowchart TD
    subgraph JPAQuery["Standard JPA Repository"]
        Q1["judgmentRepository.findById(id)"] --> R1["Hibernate appends:<br/>WHERE id = ? AND deleted_at IS NULL"]
        R1 --> Fail["Always returns null"]
    end
    subgraph NativeSQL["AdminTrashService (Spring JDBC)"]
        Q2["NamedParameterJdbcTemplate"] --> R2["Native SQL:<br/>SELECT ... WHERE deleted_at IS NOT NULL"]
        R2 --> Success["Lists and restores deleted rows"]
    end

Implementing AdminTrashService with NamedParameterJdbcTemplate

Rather than fighting Hibernate with session filters or duplicate unmapped entities, I separated the trash bin into a dedicated service backed by Spring JDBC (NamedParameterJdbcTemplate).

One critical detail: native UPDATE statements bypass the JPA persistence context, which means @LastModifiedDate, @LastModifiedBy, and @Version listeners do not run automatically. You must update updated_at, updated_user, and version = version + 1 explicitly in the SQL (especially if your edit screens rely on JPA @Version optimistic locking).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// src/main/kotlin/com/example/server/admin/application/AdminTrashService.kt
package com.example.server.admin.application

import com.example.server.admin.dto.AdminTrashRow
import com.example.server.common.BusinessException
import java.time.OffsetDateTime
import java.util.UUID
import org.springframework.data.domain.AuditorAware
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException

@Service
@Transactional(readOnly = true)
class AdminTrashService(
    private val jdbc: NamedParameterJdbcTemplate,
    private val auditorAware: AuditorAware<String>,
) {

    enum class Type(val table: String, val label: String) {
        USERS("users", "User"),
        JUDGES("judges", "Judge"),
        JUDGMENTS("judgments", "Judgment"),
        ARTICLES("articles", "Article");

        val key: String get() = name.lowercase()
        companion object {
            fun of(key: String): Type = entries.find { it.key == key }
                ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Unsupported trash type.")
        }
    }

    /**
     * Lists soft-deleted records using native SQL.
     */
    fun list(type: Type, pageable: Pageable): Page<AdminTrashRow> {
        val params = mapOf("limit" to pageable.pageSize, "offset" to pageable.offset)
        val sql = LIST_SQL.getValue(type) + " ORDER BY t.deleted_at DESC LIMIT :limit OFFSET :offset"

        val rows = jdbc.query(sql, params) { rs, _ ->
            AdminTrashRow(
                id = rs.getString("id"),
                label = rs.getString("label"),
                detail = rs.getString("detail"),
                deletedAt = rs.getObject("deleted_at", OffsetDateTime::class.java).toInstant(),
                deletedBy = rs.getString("updated_user"),
                blockedReason = if (rs.getBoolean("blocked")) BLOCKED_REASON.getValue(type) else null,
            )
        }
        val total = jdbc.queryForObject(
            "SELECT COUNT(*) FROM ${type.table} WHERE deleted_at IS NOT NULL",
            emptyMap<String, Any>(),
            Long::class.java
        ) ?: 0

        return PageImpl(rows, pageable, total)
    }

    /**
     * Restores a soft-deleted record and manually bumps audit columns and @Version.
     */
    @Transactional
    fun restore(type: Type, id: String) {
        val key: Any = when (type) {
            Type.USERS -> runCatching { UUID.fromString(id) }.getOrElse { throw notFound() }
            else -> id.toLongOrNull() ?: throw notFound()
        }

        when (type) {
            Type.USERS -> restoreUser(key as UUID)
            Type.ARTICLES -> {
                // Ensure the parent judgment is active before restoring the article
                val blocked = jdbc.queryForObject(
                    "SELECT COUNT(*) FROM articles a JOIN judgments j ON j.id = a.judgment_id " +
                    "WHERE a.id = :id AND j.deleted_at IS NOT NULL",
                    mapOf("id" to key), Long::class.java
                ) ?: 0
                if (blocked > 0) throw BusinessException(AdminErrorCode.RESTORE_ARTICLE_JUDGMENT_DELETED)
                undelete(type, key)
            }
            else -> undelete(type, key)
        }
    }

    /**
     * Restores a user by stripping the @deleted_ suffix after verifying the original email is free.
     */
    private fun restoreUser(id: UUID) {
        val email = jdbc.queryForList(
            "SELECT email FROM users WHERE id = :id AND deleted_at IS NOT NULL",
            mapOf("id" to id), String::class.java
        ).firstOrNull() ?: throw notFound()

        val original = email.replace(DELETED_EMAIL_SUFFIX, "")
        val taken = jdbc.queryForObject(
            "SELECT COUNT(*) FROM users WHERE email = :email AND deleted_at IS NULL",
            mapOf("email" to original), Long::class.java
        ) ?: 0

        if (taken > 0) throw BusinessException(AdminErrorCode.RESTORE_EMAIL_TAKEN)

        jdbc.update("UPDATE users SET email = :email WHERE id = :id", mapOf("email" to original, "id" to id))
        undelete(Type.USERS, id)
    }

    private fun undelete(type: Type, id: Any) {
        val updated = jdbc.update(
            "UPDATE ${type.table} SET deleted_at = NULL, updated_at = :now, " +
            "updated_user = :auditor, version = version + 1 " +
            "WHERE id = :id AND deleted_at IS NOT NULL",
            mapOf("now" to OffsetDateTime.now(), "auditor" to auditorAware.currentAuditor.orElse(null), "id" to id)
        )
        if (updated == 0) throw notFound()
    }

    private fun notFound() = ResponseStatusException(HttpStatus.NOT_FOUND, "Item not found in trash.")

    companion object {
        private val DELETED_EMAIL_SUFFIX = Regex("@deleted_\\d{8}-\\d{6}$")

        private val LIST_SQL = mapOf(
            Type.USERS to "SELECT CAST(t.id AS VARCHAR(36)) AS id, t.nickname AS label, t.email AS detail, t.deleted_at, t.updated_user, FALSE AS blocked FROM users t WHERE t.deleted_at IS NOT NULL",
            Type.JUDGES to "SELECT CAST(t.id AS VARCHAR(20)) AS id, t.name AS label, t.court AS detail, t.deleted_at, t.updated_user, FALSE AS blocked FROM judges t WHERE t.deleted_at IS NOT NULL",
            Type.JUDGMENTS to "SELECT CAST(t.id AS VARCHAR(20)) AS id, t.case_number AS label, t.verdict AS detail, t.deleted_at, t.updated_user, FALSE AS blocked FROM judgments t WHERE t.deleted_at IS NOT NULL",
            Type.ARTICLES to "SELECT CAST(t.id AS VARCHAR(20)) AS id, t.title AS label, j.case_number AS detail, t.deleted_at, t.updated_user, (j.deleted_at IS NOT NULL) AS blocked FROM articles t JOIN judgments j ON j.id = t.judgment_id WHERE t.deleted_at IS NOT NULL",
        )

        private val BLOCKED_REASON = mapOf(
            Type.ARTICLES to "The source judgment is still deleted. Restore the judgment first."
        ).withDefault { "" }
    }
}

Verification and integration tests

1. Soft delete via the admin row action menu

On /admin/articles and /admin/judgments, operators click the row overflow menu (⋯) or right-click to move a record to the trash bin:

Admin article list row context menu and delete confirmation modal Figure 1. Admin list row menu and confirmation dialog. Confirming sends a CSRF-protected POST /admin/articles/{id}/delete request.

2. Trash bin dashboard and restore flow

Deleted rows appear under /admin/trash, grouped by entity type (Users, Judges, Judgments, Articles):

Admin trash bin dashboard showing deleted items and restore actions Figure 2. Admin trash bin dashboard. Each row shows who deleted it, when it was deleted, and disables restore if a required parent record is still deleted.

  • Audit trail preserved: Operators can see exactly who deleted each record and when.
  • Referential guard (BLOCKED_REASON): Articles whose source judgment is still in the trash display a disabled restore button so restoring never creates orphan references.
  • Direct restore: Clicking Restore clears deleted_at, increments version, and returns the record to the active admin list.

3. Integration tests for partial index and restore conflicts

Here are the integration tests verifying the full delete-and-restore lifecycle and email re-registration behavior:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// src/test/kotlin/com/example/server/admin/AdminTrashTest.kt
package com.example.server.admin

import com.example.server.support.IntegrationTestSupport
import com.example.server.judgment.domain.Judge
import com.example.server.judgment.domain.JudgeJpaRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.repository.findByIdOrNull
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post

@DisplayName("Admin trash bin (list and restore soft-deleted rows)")
class AdminTrashTest : IntegrationTestSupport() {

    @Autowired
    private lateinit var judgeRepository: JudgeJpaRepository

    @Test
    fun `deleted judge appears in trash and returns to active list after restore`() {
        val admin = login(createAdmin(nickname = "moderator"))
        val judge = judgeRepository.save(Judge(name = "Judge Kim"))

        // Soft delete
        mockMvc.post("/admin/judges/${judge.id}/delete") { cookie(admin) }

        // Verify presence in trash
        mockMvc.get("/admin/trash") { cookie(admin); param("type", "judges") }
            .andExpect { status { isOk() } }

        // Restore
        mockMvc.post("/admin/trash/judges/${judge.id}/restore") { cookie(admin) }

        // Confirm deletedAt is cleared and version incremented
        val restored = judgeRepository.findByIdOrNull(judge.id)!!
        assertThat(restored.deletedAt).isNull()
        assertThat(restored.version).isGreaterThan(judge.version)
    }

    @Test
    fun `blocks user restore when an active account already owns the original email`() {
        val admin = login(createAdmin())
        val email = "reuse@example.com"
        val user = createUser(email = email)

        // 1. Soft-delete user
        mockMvc.post("/admin/users/${user.id}/delete") { cookie(admin) }

        // 2. Another user registers with the same email (allowed by partial unique index)
        createUser(email = email)

        // 3. Restoring the original user must fail due to email collision
        mockMvc.post("/admin/trash/users/${user.id}/restore") { cookie(admin) }
            .andExpect {
                flash { attribute("error", "Cannot restore user because an active account already uses this email.") }
            }
    }
}

Running the suite alongside psql confirms the partial index definition and passing test results:

Integration test output and PostgreSQL partial unique index verification Figure 3. PostgreSQL index definition (uk_users_email_active ... WHERE (deleted_at IS NULL)) and passing integration tests for soft delete, re-registration, and restore conflict detection.


Caveats and checklist

Soft delete is not always the right default. If a table accumulates millions of high-churn rows (such as session tokens or ephemeral webhook logs), keeping deleted rows in the hot table bloats indexes and slows scans—use hard deletes or an archive table instead. Also note that MySQL does not support WHERE predicates on indexes; on MySQL 8+, you need a generated column (e.g., active_email VARCHAR(255) GENERATED ALWAYS AS (IF(deleted_at IS NULL, email, NULL))) with a standard unique index.

Production checklist:

  • Replace UNIQUE (col, deleted_at) with CREATE UNIQUE INDEX ... ON table (col) WHERE deleted_at IS NULL in PostgreSQL.
  • Put @SQLRestriction("deleted_at IS NULL") on your shared BaseEntity so normal JPA queries never leak deleted rows.
  • Isolate trash-bin queries and restores in a NamedParameterJdbcTemplate service instead of working around @SQLRestriction inside JPA.
  • Update updated_at, updated_user, and version = version + 1 explicitly in native restore queries, and validate parent/unique dependencies before clearing deleted_at.
This post is licensed under CC BY 4.0 by the author.