Communitygithub.com

JPA/Hibernate模式

Spring Boot 中用于实体设计、关系映射、查询优化、事务管理、审计、索引、分页和连接池的 JPA/Hibernate 模式。当设计 JPA 实体或关系,或者需要修复 Hibernate 查询、事务或 N+1 问题时使用。

Hibernate模式 是什么?

该技能为使用 Spring Boot 进行数据访问的开发者提供了一套全面的 JPA/Hibernate 最佳实践指南。它涵盖了从实体设计、关系映射(@OneToMany、@ManyToOne、@ManyToMany)到 N+1 查询预防、事务管理、审计和软删除等所有关键方面。技能还涉及存储库模式、分页与排序、HikariCP 连接池调优、二级缓存策略,以及 Flyway/Liquibase 的数据库迁移管理。性能优化部分包括索引最佳实践、JPQL 中的 JOIN FETCH 使用方法以及 DTO 投影以减少数据加载。此外,它还强调了使用 @DataJpaTest 和 Testcontainers 进行测试的重要性,确保开发人员能够编写高效的、适合生产环境的数据访问层。该技能适用于 Claude Code、Cursor 等 AI 代理,遵循标准的 Spring Data JPA 约定。

兼容平台~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 中的数据建模、存储库和性能调优。

何时激活

  • 设计 JPA 实体和表映射
  • 定义关系(@OneToMany、@ManyToOne、@ManyToMany)
  • 优化查询(N+1 预防、抓取策略、投影)
  • 配置事务、审计或软删除
  • 设置分页、排序或自定义存储库方法
  • 调优连接池(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);

存储库模式

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.

相关技能