Communitygithub.com

jpa-patterns

JPA/Hibernate 模式,用於 Spring Boot 中的實體設計、關聯、查詢最佳化、交易、審計、索引、分頁與連線池。

jpa-patterns 是什麼?

這項技能提供了一套完整的 JPA/Hibernate 模式,專為在 Spring Boot 環境中進行資料建模與效能調校而設計。它涵蓋了實體設計與表格映射、關聯(如 @OneToMany、@ManyToOne、@ManyToMany)定義、N+1 查詢問題的預防與擷取策略最佳化,以及交易與審計配置。支援分頁、排序與自訂 Repository 方法,也包含 HikariCP 連線池調校與第二級快取的建議。這項技能適合在需要設計 JPA 實體或 Hibernate 查詢與交易時使用,並提供實際的程式碼範例與組態屬性,協助開發者避免常見的資料存取陷阱。適用於 CLI 環境的程式碼輔助與智能 IDE 的整合開發。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/jpa-patterns

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

JPA/Hibernate 模式

用於 Spring Boot 中的資料建模、Repository 與效能調校。

啟用時機

  • 設計 JPA 實體與表格映射
  • 定義關聯 (@OneToMany, @ManyToOne, @ManyToMany)
  • 最佳化查詢 (N+1 預防、擷取策略、投影)
  • 配置交易、審計或軟刪除
  • 設定分頁、排序或自訂 Repository 方法
  • 調校連線池 (HikariCP) 或第二級快取

實體設計

@Entity
@Table(name = "markets", indexes = {
  @Index(name = "idx_markets_slug", columnList = "slug", unique = true)
})
@EntityListeners(AuditingEntityListener.class)
public class MarketEntity {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(nullable = false, length = 200)
  private String name;

  @Column(nullable = false, unique = true, length = 120)
  private String slug;

  @Enumerated(EnumType.STRING)
  private MarketStatus status = MarketStatus.ACTIVE;

  @CreatedDate private Instant createdAt;
  @LastModifiedDate private Instant updatedAt;
}

啟用審計:

@Configuration
@EnableJpaAuditing
class JpaConfig {}

關聯與 N+1 預防

@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
  • 預設為延遲載入;需要時在查詢中使用 JOIN FETCH
  • 對集合避免使用 EAGER;對讀取路徑使用 DTO 投影
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);

Repository 模式

public interface MarketRepository extends JpaRepository<MarketEntity, Long> {
  Optional<MarketEntity> findBySlug(String slug);

  @Query("select m from MarketEntity m where m.status = :status")
  Page<MarketEntity> findByStatus(@Param("status") MarketStatus status, Pageable pageable);
}
  • 對輕量級查詢使用投影:
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);

交易

  • 在服務方法上加上 @Transactional 註解
  • 對讀取路徑使用 @Transactional(readOnly = true) 以最佳化
  • 謹慎選擇傳播行為;避免長時間執行的交易
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
  MarketEntity entity = repo.findById(id)
      .orElseThrow(() -> new EntityNotFoundException("Market"));
  entity.setStatus(status);
  return Market.from(entity);
}

分頁

PageRequest page = PageRequest.of(pageNumber, pageSize, Sort.by("createdAt").descending());
Page<MarketEntity> markets = repo.findByStatus(MarketStatus.ACTIVE, page);

若要類比游標式分頁,可在 JPQL 中加入 id > :lastId 條件並配合排序。

索引與效能

  • 為常見的篩選條件 (status, slug, 外鍵) 加入索引
  • 使用複合索引以符合查詢模式 (status, created_at)
  • 避免 select *;只投影所需的欄位
  • 使用 saveAll 和 hibernate.jdbc.batch_size 進行批次寫入

連線池 (HikariCP)

建議的屬性:

spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.validation-timeout=5000

對於 PostgreSQL 的 LOB 處理,請加上:

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

快取

  • 第一級快取是 EntityManager 層級;避免在不同交易之間保留實體
  • 對讀取頻繁的實體,謹慎考慮第二級快取;務必驗證清除策略

遷移

  • 使用 Flyway 或 Liquibase;生產環境絕不依賴 Hibernate 自動 DDL
  • 保持遷移的冪等性與累加性;未經計畫不要刪除欄位

測試資料存取

  • 偏好使用 @DataJpaTest 搭配 Testcontainers 來模擬生產環境
  • 透過日誌驗證 SQL 效率:設定 logging.level.org.hibernate.SQL=DEBUG 以及 logging.level.org.hibernate.orm.jdbc.bind=TRACE 以檢視參數值

切記:保持實體精簡、查詢有目的、交易簡短。使用擷取策略與投影預防 N+1,並為讀寫路徑建立索引。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能