Skip to content
All Skills

Kotlin Backend Jpa Entity Mapping

Model Kotlin persistence code correctly for Spring Data JPA and Hibernate. Covers entity design, identity and equality, uniqueness constraints, relationships, fetch plans, and common ORM (Object-Relational Mapping) traps specific to Kotlin. Use when creating or reviewing JPA (Java Persistence API) entities, diagnosing N+1 or LazyInitializationException, placing indexes and uniqueness rules, or preventing Kotlin-specific bugs such as data class entities and broken equals/hashCode.

Software Engineering|v1|Updated 7/14/2026|GitHub source
MCP get_skill({ skillId: "kotlin-backend-jpa-entity-mapping-c99cac30" })

Use this skill with your agent

Create a free account and connect via MCP

Get Started Free
# JPA Entity Mapping for Kotlin

Kotlin's `data class` is natural for DTOs but dangerous for JPA entities. Hibernate relies on
identity semantics that `data class` breaks: `equals`/`hashCode` over all fields corrupts
`Set`/`Map` membership after state changes, and auto-generated `copy()` creates detached
duplicates of managed entities.

This skill teaches correct entity design, identity strategies, and uniqueness constraints
for Kotlin + Spring Data JPA projects.

## Entity Design Rules

- **Never use `data class` for JPA entities.** Use a regular `class`. Keep `data class` for DTOs.
- Keep transport DTOs and persistence entities separate unless the project clearly uses a shared model.
- Model required columns as non-null only when object construction and persistence lifecycle make it safe.
- Use `lateinit` only when the project already accepts that tradeoff and the lifecycle is safe.
- Verify `kotlin("plugin.jpa")` or equivalent no-arg support when JPA entities exist.
- Verify classes and members are compatible with proxying where needed.

## Identity and Equality

- Never accept all-field `equals`/`hashCode` generated by `data class` on an entity.
- Follow project conventions when they already define an identity strategy.
- If no convention exists, use ID-based equality with a stable `hashCode`.
- For DB-generated IDs, model the unsaved state with nullable `var id: Long? = null`
  and a `protected set`; do not use `0L` as a sentinel value.
- Be explicit about mutable fields and lazy associations when discussing equality.

### Broken: `data class` Entity

```kotlin
// WRONG: data class generates equals/hashCode from ALL fields,
// and the generated ID uses a 0 sentinel instead of null
data class Order(
    @Id @GeneratedValue val id: Long = 0,
    var status: String,
    var total: BigDecimal
)
// BUG: order.status = "SHIPPED"; set.contains(order) → false (hash changed)
// BUG: Hibernate proxy.equals(entity) → false (proxy has lazy fields uninitialized)
```

### Correct: Regular Class with ID-Based Identity

```kotlin
@Entity
@Table(name = "orders")
class Order(
    @Column(nullable = false)
    var status: String,

    @Column(nullable = false)
    var total: BigDecimal
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null
        protected set

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Order) return false
        return id != null && id == other.id
    }

    override fun hashCode(): Int = javaClass.hashCode()

    // toString must NOT reference lazy collections
    override fun toString(): String = "Order(id=$id, status=$status)"
}
```

**Key rules:**
- `equals` compares by ID only — stable under dirty tracking and proxy unwrapping
- `hashCode` returns class-based constant — avoids `Set`/`Map` corruption after persist
- `toString` excludes lazy-loaded relations — prevents `LazyInitializationException`
- Constructor params are mutable entity fields; DB-generated `id` is nullable with a protected setter

## Uniqueness Constraints

When an API must be idempotent (e.g., "reserve stock for order X"), enforce uniqueness
at both layers: database constraint for correctness, application check for clean errors.

### Broken: No Duplicate Guard

```kotlin
@Service
class ReservationService(private val repo: ReservationRepository) {
    @Transactional
    fun createReservation(variantId: Long, orderId: String, qty: Int): Reservation {
        // BUG: no check — duplicates silently accumulate
        return repo.save(Reservation(variantId = variantId, orderId = orderId, quantity = qty))
    }
}
```

### Correct: Database Constraint + Application Guard

```kotlin
@Entity
@Table(
    name = "reservations",
    uniqueConstraints = [
        UniqueConstraint(columnNames = ["variant_id", "order_id"])
    ]
)
class Reservation(
    @Column(name = "variant_id", nullable = false)
    val variantId: Long,

    @Column(name = "order_id", nullable = false)
    val orderId: String,

    @Column(nullable = false)
    var quantity: Int
) {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null
        protected set
}

interface ReservationRepository : JpaRepository<Reservation, Long> {
    fun findByVariantIdAndOrderId(variantId: Long, orderId: String): Reservation?
}

@Service
class ReservationService(private val repo: ReservationRepository) {
    @Transactional
    fun createReservation(variantId: Long, orderId: String, qty: Int): Reservation {
        repo.findByVariantIdAndOrderId(variantId, orderId)?.let {
            throw IllegalStateException(
                "Reservation already exists for variant=$variantId, order=$orderId"
            )
        }
        return repo.save(Reservation(variantId = variantId, orderId = orderId, quantity = qty))
    }
}
```

**Key rules:**
- Database constraint is mandatory — application checks alone have race conditions
- Application check provides clean error messages — without it, users get raw `DataIntegrityViolationException`
- Both layers together: application catches the common case, database catches the race
- Spring Data derives `findByXAndY` queries automatically

## Query and Fetch Rules

- Diagnose N+1 by looking at actual query count or SQL logs, not by guessing from annotations.
- Prefer targeted fetch solutions: `@EntityGraph`, `JOIN FETCH`, batch fetching, or DTO projection.
- Be careful with collection fetch joins plus pagination — call out the tradeoff.
- Use indexes and uniqueness constraints to support real query patterns.

## Common ORM Traps

- **Bidirectional associations:** maintain both sides in domain methods. Half-updated graphs cause subtle bugs.
- **`orphanRemoval` vs cascade remove:** not interchangeable. Explain lifecycle semantics before choosing.
- **Lazy load triggers:** `toString`, debug logging, JSON serialization, and IDE inspection can all trigger lazy loads.
- **Bulk updates/deletes:** bypass persistence context and lifecycle callbacks. Subsequent reads may be stale.
- **Multiple bag fetches:** can cause Cartesian explosion. Verify the ORM can execute collection-heavy fetch plans safely.
- **`Set` + mutable equality:** collection membership can break after entity state changes.
- **`@Version`:** the clearest optimistic concurrency mechanism when concurrent updates matter.
- **`open-in-view` disabled:** DTO mapping touching lazy fields must happen inside a transaction boundary.

## Guardrails

- Do not use `data class` for JPA entities.
- Do not recommend `FetchType.EAGER` everywhere to silence lazy loading symptoms.
- Do not expose entities directly through API responses by default.
- Do not claim an N+1 fix without explaining how the fetch plan changes query behavior.
#kotlin#jvm#android#database#design

Related Skills

More skills in Software Engineering

Accessibility Standards

Comprehensive web accessibility standards based on WCAG 2.2 AA, with 38+ anti-patterns, legal enforcement context (EAA, ADA Title II), WAI-ARIA patterns, and framework-specific fixes for modern web frameworks and libraries.

#github-copilot#accessibilityMIT

Accord

Authoring unified specification packages across Business/Development/Design teams via staged elaboration (L0 Vision → L1 Requirements → L2 Team Detail → L3 Acceptance Criteria). No code. Use when authoring cross-team specs, building L0-L3 packages, or aligning Biz/Dev/Design on a single source of truth.

#broad-capability#developmentMIT

Acquire Codebase Knowledge

Use this skill when the user explicitly asks to map, document, or onboard into an existing codebase. Trigger for prompts like "map this codebase", "document this architecture", "onboard me to this repo", or "create codebase docs". Do not trigger for routine feature implementation, bug fixes, or narrow code edits unless the user asks for repository-level discovery.

#github-copilot#documentationMIT

Acreadiness Assess

Run the AgentRC readiness assessment on the current repository and produce a static HTML dashboard at reports/index.html. Wraps `npx github:microsoft/agentrc readiness` and hands off rendering to the @ai-readiness-reporter custom agent. Supports policies (--policy) for org-specific scoring. Use when asked to assess, audit, or score the AI readiness of a repo.

#github-copilot#planningMIT

Acreadiness Generate Instructions

Generate tailored AI agent instruction files via AgentRC instructions command. Produces .github/copilot-instructions.md (default, recommended for Copilot in VS Code) plus optional per-area .instructions.md files with applyTo globs for monorepos. Use after running /acreadiness-assess to close gaps in the AI Tooling pillar.

#github-copilot#skillMIT

Acreadiness Policy

Help the user pick, write, or apply an AgentRC policy. Policies customise readiness scoring by disabling irrelevant checks, overriding impact/level, setting pass-rate thresholds, or chaining org baselines with team overrides. Use when the user asks about strict mode, AI-only scoring, custom weights, CI gating, or wants org-wide standardisation.

#github-copilot#planningMIT

Explore Other Categories

Skills from other categories with shared topics

Avoiding Subcomposition Pitfalls

Use this skill when a Compose tree uses SubcomposeLayout, BoxWithConstraints, or Scaffold and the developer reports extra measure passes, slow first frame, or layout passes running content composition repeatedly. Covers why SubcomposeLayout composes its slots during the measure phase, why BoxWithConstraints forces a subcomposition for every new Constraints value, why nesting Scaffold or BoxWithConstraints multiplies the cost, when a custom Layout or Modifier.layout { } replaces SubcomposeLayout, and how to use SubcomposeLayoutState's slot reuse policy and precompose APIs when SubcomposeLayout is genuinely required. Use when the developer mentions BoxWithConstraints, SubcomposeLayout, Scaffold, "extra measure pass", "double measurement", "first frame slow", "subcompose", or notices that wrapping content in BoxWithConstraints regresses scroll perf inside a LazyColumn.

Mobile App Development#android#jetpack-compose

Choosing Derivedstateof

Use this skill to decide when Jetpack Compose derivedStateOf is the right tool and when it is pure overhead. Covers the "input frequency must exceed output frequency" rule, the mandatory remember { derivedStateOf { } } wrapper, the canonical pitfall of capturing non-state variables by initial value (and the remember(key) fix), and the snapshotFlow alternative for fire-and-forget side effects on derived values. Use when the developer mentions derivedStateOf, scroll-position-driven booleans, threshold checks, firstVisibleItemIndex, "show FAB on scroll", recomposition counts that don't drop after wrapping a value, or asks whether a computed string concatenation should use derivedStateOf.

Mobile App Development#android#jetpack-compose

Collecting Flows Safely

Use this skill to migrate Compose UI from `collectAsState()` to `collectAsStateWithLifecycle()`, hoist `Flow<T>` parameters out of composables, and apply `.conflate()` / `.distinctUntilChanged()` / `snapshotFlow` so background CPU and battery stop draining and chatty flows stop invalidating the UI per emission. Covers ViewModel `StateFlow`/`SharedFlow` consumers, sensor and location streams, and the "Flow as composable parameter" antipattern. Trigger when the user mentions `collectAsState`, `collectAsStateWithLifecycle`, lifecycle-aware flow collection, `Lifecycle.State.STARTED`, background battery drain from a Compose screen, `snapshotFlow`, `Flow` parameter on a composable, conflate, or distinctUntilChanged.

Mobile App Development#android#jetpack-compose