jpa-spring-data-kotlin-mapper

par kotlin

Modèle correctement le code de persistance Kotlin pour Spring Data JPA et Hibernate, y compris la conception des entités, les relations, les plans de chargement, les requêtes de repository, le chargement paresseux…

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.

Plus de skills de kotlin

ci-cd-containerization-advisor
kotlin
Concevoir des pipelines de construction, d'image et de déploiement reproductibles pour les applications Kotlin et Spring, incluant la vérification CI, les conteneurs en couches, la sécurité de déploiement,…
official
configuration-properties-profiles-kotlin-safe
kotlin
Design and diagnose Spring configuration, profiles, and `@ConfigurationProperties` binding for Kotlin applications. Use when property binding fails,…
official
dependency-conflict-resolver
kotlin
Diagnose and resolve Gradle and Spring classpath conflicts, version drift, and binary incompatibilities in Kotlin applications. Use when `NoSuchMethodError`,…
official
domain-decomposition-api-design-advisor
kotlin
Décomposer le périmètre métier en contextes délimités, en limites de modules ou de services, en workflows et en contrats d'API avant le début de l'implémentation. À utiliser lors de l'élaboration d'un nouveau…
official
error-model-validation-architect
kotlin
Concevoir et implémenter un comportement cohérent de validation des API et de gestion des erreurs pour les services Kotlin et Spring. À utiliser lors de la définition des charges utiles d'erreur, du mappage du framework…
official
gradle-kotlin-dsl-doctor
kotlin
Generate, debug, and repair Kotlin + Spring Gradle builds with minimal, compatible changes. Use when `build.gradle.kts` or `settings.gradle.kts` is failing,…
official
integration-resilience-engineer
kotlin
Concevoir des intégrations HTTP, de messagerie et planifiées résilientes pour les services Kotlin et Spring avec des budgets de délai d'attente explicites, des tentatives, de l'idempotence, des circuits…
official
jackson-kotlin-serialization-specialist
kotlin
Diagnostiquer et concevoir le comportement de sérialisation et désérialisation JSON pour Kotlin avec Jackson dans les applications Spring. Utiliser lorsque les DTO échouent à la désérialisation, par défaut…
official