跳到主内容
智客 ZICQ

技能库 智客分类:设计创意 kotlin-backend-jpa-entity-mapping

Kotlin Backend Jpa Entity Mapping

Spring Data JPA和Hibernate的模型克特林恒定码正确. 覆盖实体设计,身份与平等,独有性限制,关系,取取计划,以及克特林特有的常见ORM(对象-关系映射)陷阱. 在创建或审查JPA(Java Persistence API)实体时使用,诊断N+1或LazyInitializationException,放置索引和独有性规则,或防止克特林特定的bug,如数据类实体和断等/hashCode.

1289 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

Spring Data JPA和Hibernate的模型克特林恒定码正确. 涵盖实体设计、身份和平等、独特性限制、关系、获取计划以及科特林特有的常见ORM(对象-关系绘图)陷阱

何时用

创建或审查 JPA (Java Persistence API) 实体, 诊断 N+1 或 Lazy Initialization Exception, 放置索引和独有性规则, 或防止 Kotlin 特定错误, 如数据类实体和损坏等同/ hashCode

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:JPA Entity Mapping for Kotlin、Entity Design Rules、Identity and Equality、Broken: `data class` Entity、Correct: Regular Class with ID-Based Identity、Uniqueness Constraints。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 description(原文)

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.

JPA Entity Mapping for KotlinEntity Design RulesIdentity and EqualityBroken: `data class` EntityCorrect: Regular Class with ID-Based IdentityUniqueness ConstraintsBroken: No Duplicate GuardCorrect: Database Constraint + Application GuardQuery and Fetch RulesCommon ORM TrapsGuardrails

· 许可:Apache-2.0

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
kotlin-backend-jpa-entity-mapping
description
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.
许可
Apache-2.0
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「kotlin-backend-jpa-entity-mapping」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-a97bfd5c8d1c6962-Kotlin-%E5%90%8E%E7%AB%AF-Jpa-%E5%AE%9E%E4%BD%93%E7%BB%98%E5%9B%BE.html
请存为 .cursor/skills/kotlin-backend-jpa-entity-mapping/SKILL.md 或 .claude/skills/kotlin-backend-jpa-entity-mapping/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/kotlin/kotlin-agent-skills' --list

npx skills add 'https://github.com/kotlin/kotlin-agent-skills' --skill 'kotlin-backend-jpa-entity-mapping'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: kotlin-backend-jpa-entity-mapping description: > 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. license: Apache-2.0 metadata: author: JetBrains version: "1.0.0" --- # 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 { 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.

相关技能

设计创意

Automation Workflows

设计和实施自动化工作流程,以节省时间和规模化操作作为独家. 用于识别重复任务实现自动化,构建跨工具的工作流程,设置触发器和行动,或优化现有自动化. 包括自动化机会识别,工作流程设计,工具选择(Zapier,Make,n8n),测试,和维护. 触发"自动","自动","工作流程自动…

设计创意

Ui Ux Pro Max

UI/UX设计智能及建筑抛光接口实施指导. 当用户要求UI设计,UX流量,信息架构,视觉风格方向,设计系统/托盘,组件规格,副本/显微镜,可访问性,或生成/critique/refine前端UI(HTML/CSS/JS,React,Next.js,Vue,Svelte,Tailw…

设计创意

Frontend Design

创建美丽现代UI的专家前端设计指南. 在构建起落架页面,仪表板,或任何用户界面时使用.

设计创意

N8n Workflow Automation

设计和输出 n8n 工作流程 JSON 有强力触发器, idempotency, 错误处理, 记录, 重试, 以及 人入"一站"审查队列. 当您需要可审计的自动化时使用.