jpa-spring-data-kotlin-mapper

作者: kotlin

為Spring Data JPA和Hibernate正確建模Kotlin持久化代碼,包括實體設計、關聯關係、擷取計劃、儲存庫查詢、懶加載…

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 所破壞的識別語義:基於所有欄位的 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 原始碼轉換為慣用的 Kotlin,並在每一步驟檢查五個不變量。支援框架感知轉換,能處理註解站點目標、函式庫慣用語及 API 保留。
kotlin-tooling-native-build-performance
kotlin
診斷並修復針對 iOS 的 Kotlin Multiplatform 專案中,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 驗證、分層容器、部署安全性……