jpa-spring-data-kotlin-mapper

작성자: kotlin

Kotlin 지속성 코드를 Spring Data JPA 및 Hibernate에 맞게 올바르게 모델링하며, 엔티티 설계, 관계, 페치 계획, 리포지토리 쿼리, 지연 로딩 등을 포함합니다.

npx skills add https://github.com/kotlin/kotlin-backend-agent-skills --skill jpa-spring-data-kotlin-mapper

JPA Spring Data Kotlin Mapper

Source mapping: Tier 1 critical skill derived from Kotlin_Spring_Developer_Pipeline.md (SK-10).

Mission

Generate and review persistence mappings that are correct for both Hibernate semantics and Kotlin semantics. Prevent bugs that compile cleanly but fail under lazy loading, dirty checking, identity comparison, or query load.

Read First

  • Entity classes and mapped superclasses.
  • Repository interfaces and custom queries.
  • Relevant service methods and transaction boundaries.
  • SQL logs, execution plans, or symptoms such as N+1, deadlocks, or stale reads.
  • Build files to verify JPA-related Kotlin compiler plugins.

Entity Design Rules

  • Do not generate JPA entities as data class.
  • Keep transport DTOs and persistence entities separate unless the repository clearly uses a shared model on purpose.
  • Model required columns as non-null only when object construction and persistence lifecycle make that safe.
  • Treat lazy associations and optional associations carefully. Nullable is often the honest model.
  • Use lateinit only when the project already accepts that tradeoff and the lifecycle is safe.

Identity And Equality Rules

  • Never accept all-field equals and hashCode generated by a data class entity.
  • Follow project conventions when they already define an entity identity strategy.
  • If no convention exists, choose an identity approach that is stable under persistence and proxying, then explain the tradeoff.
  • Be explicit about mutable fields and lazy associations when discussing equality semantics.

Query And Fetch Rules

  • Diagnose N+1 by looking at actual query count or SQL logs, not by guessing from annotations alone.
  • Prefer targeted fetch solutions:
    • @EntityGraph
    • JOIN FETCH
    • batch fetching
    • DTO projection
  • Be careful with collection fetch joins plus pagination. Call out the tradeoff instead of hiding it.
  • Use indexes and uniqueness constraints to support real query patterns and idempotency guarantees.

Advanced ORM Traps

  • Maintain both sides of bidirectional associations in domain methods or helper functions. Half-updated object graphs are a common source of subtle bugs.
  • orphanRemoval and cascade remove are not interchangeable. Explain the lifecycle semantics before choosing one.
  • toString, debug logging, JSON serialization, and IDE inspection can trigger lazy loads. Treat them as potential side effects, not harmless utilities.
  • Bulk update or delete queries bypass the persistence context and lifecycle callbacks. Call out when subsequent reads may be stale until clear or reload.
  • Multiple bag fetches can explode under Hibernate. If a collection-heavy fetch plan looks "obviously convenient," verify whether the ORM can execute it safely.
  • Set-based collections plus mutable equality are especially dangerous. Collection membership can break after entity state changes.
  • @Version is usually the clearest optimistic concurrency mechanism when concurrent updates matter. Mention it explicitly when the use case can lose updates.
  • If open-in-view is disabled, DTO mapping that touches lazy fields must happen inside a deliberate transaction boundary.

Expert Heuristics

  • Choose entity shape for write correctness first and read shape second. If reads need a different shape, use projections or dedicated queries.
  • If a query is hot and read-only, DTO projection is often a better optimization than tuning entity graphs indefinitely.
  • If a relationship exists only to simplify one query, question whether it belongs in the entity model or in a query model.
  • Treat database indexes as part of the persistence design, not as a late production optimization.

Kotlin-Specific Checks

  • Verify kotlin("plugin.jpa") or equivalent no-arg support when JPA entities exist.
  • Verify classes and members are compatible with proxying where needed.
  • Verify nullability reflects database truth rather than wishful API design.
  • Verify repository return types and service expectations agree on null handling.

Output Contract

Return these sections:

  • Persistence model: the entity and relationship shape that should exist.
  • Correctness risks: identity, lazy loading, transactional access, and nullability traps.
  • Performance risks: N+1, fetch plan, query shape, pagination, and index concerns.
  • Recommended changes: entity, repository, and query updates in minimal-diff form.
  • Verification: tests or SQL-level checks that confirm the mapping works as intended.

Guardrails

  • Do not recommend FetchType.EAGER everywhere to silence lazy loading symptoms.
  • Do not expose entities directly through API responses by default.
  • Do not use data class entities.
  • Do not claim an N+1 fix without explaining how the fetch plan changes query behavior.
  • Do not place all persistence intelligence in repositories if the service layer controls the real access pattern.

Quality Bar

A good run of this skill improves correctness and query behavior together. A bad run proposes mappings that look neat in Kotlin but violate JPA identity, proxy, or loading semantics.

kotlin의 다른 스킬

kotlin-backend-jpa-entity-mapping
kotlin
Kotlin의 data class는 DTO에 자연스럽지만 JPA 엔티티에는 위험합니다. Hibernate는 data class가 깨뜨리는 identity 의미론에 의존합니다. 모든 필드에 대한 equals/hashCode는 상태 변경 후 Set/Map 멤버십을 손상시키고, 자동 생성된 copy()는 관리되는 엔티티의 분리된 복제본을 만듭니다.
kotlin-tooling-agp9-migration
kotlin
Android Gradle Plugin 9.0은 동일한 모듈에서 Android 애플리케이션 및 라이브러리 플러그인을 Kotlin Multiplatform 플러그인과 호환되지 않게 만듭니다. 이 스킬은 마이그레이션 과정을 안내합니다.
kotlin-tooling-cocoapods-spm-migration
kotlin
KMP 프로젝트를 CocoaPods(kotlin("native.cocoapods"))에서 Swift Package Manager(swiftPMDependencies DSL)로 마이그레이션 — pod()를 swiftPackage()로 대체,…
kotlin-tooling-immutable-collections-0-5-x-migration
kotlin
Kotlin(및 Java) 코드를 kotlinx.collections.immutable 0.3.x / 0.4.x에서 최신 0.5.x로 마이그레이션합니다. 0.5.x 라인은 모든 복사본을 반환하는 메서드의 이름을 변경합니다…
kotlin-tooling-java-to-kotlin
kotlin
Java 소스 파일을 체계적인 4단계 변환 방법론을 사용하여 관용적인 Kotlin으로 변환하며, 각 단계에서 5가지 불변 조건을 확인합니다. 애노테이션 사이트 대상, 라이브러리 관용구, API 보존을 처리하는 프레임워크 인식 변환을 지원합니다.
kotlin-tooling-native-build-performance
kotlin
Kotlin Multiplatform 프로젝트에서 iOS를 대상으로 할 때 느린 Kotlin/Native 컴파일 및 링크를 진단하고 수정합니다. 사용자가 느린 iOS 또는…을 보고할 때 사용하세요.
kotlin-spring-proxy-compatibility
kotlin
Diagnose and prevent Kotlin plus Spring proxy failures around `@Transactional`, `@Cacheable`, `@Async`, method security, retry, configuration proxies, and JPA…
ci-cd-containerization-advisor
kotlin
재현 가능한 빌드, 이미지 및 배포 파이프라인을 설계합니다. Kotlin 및 Spring 애플리케이션을 대상으로 하며, CI 검증, 계층형 컨테이너, 롤아웃 안전성 등을 포함합니다.