jpa-patterns

Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

351 stars

Best use case

jpa-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "jpa-patterns" skill to help with this workflow task. Context: Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/jpa-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/xu-xiang/everything-claude-code-zh/main/docs/ja-JP/skills/jpa-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/jpa-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How jpa-patterns Compares

Feature / Agentjpa-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# JPA/Hibernate 模式

用于 Spring Boot 中的数据建模、存储库(Repository)和性能调优。

## 实体设计 (Entity Design)

```java
@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;
}
```

启用审计 (Auditing):
```java
@Configuration
@EnableJpaAuditing
class JpaConfig {}
```

## 关联关系与 N+1 问题预防

```java
@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
```

- 默认使用延迟加载(Lazy Loading)。根据需要,在查询中使用 `JOIN FETCH`。
- 集合属性应避免使用 `EAGER` 加载,在读取路径中优先使用 DTO 投影(Projection)。

```java
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);
```

## 存储库模式 (Repository Pattern)

```java
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);
}
```

- 对于轻量级查询,请使用投影(Projection):
```java
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);
```

## 事务 (Transactions)

- 在服务层(Service)方法上添加 `@Transactional` 注解。
- 使用 `@Transactional(readOnly = true)` 优化只读路径。
- 谨慎选择事务传播(Propagation)行为。避免长时间运行的事务。

```java
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
  MarketEntity entity = repo.findById(id)
      .orElseThrow(() -> new EntityNotFoundException("Market"));
  entity.setStatus(status);
  return Market.from(entity);
}
```

## 分页 (Pagination)

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

对于类似游标(Cursor)的分页,请在 JPQL 排序中包含 `id > :lastId`。

## 索引创建与性能优化

- 为常用过滤器(如 `status`、`slug`、外键)添加索引。
- 使用符合查询模式的复合索引(例如 `status, created_at`)。
- 避免使用 `select *`,仅投影必要的列。
- 利用 `saveAll` 和 `hibernate.jdbc.batch_size` 进行批量写入。

## 连接池 (Connection Pooling - 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
```

## 缓存 (Caching)

- 一级缓存(First-level Cache)是基于 EntityManager 的。不要在事务之间持有实体。
- 对于读取密集型实体,请谨慎考虑二级缓存(Second-level Cache)。验证淘汰策略(Eviction Strategy)。

## 数据库迁移 (Migration)

- 使用 Flyway 或 Liquibase。不要在生产环境中依赖 Hibernate 的自动 DDL。
- 保持迁移脚本的幂等性(Idempotent)和增量性。不要在未规划的情况下删除列。

## 数据访问测试

- 优先使用配合 Testcontainers 的 `@DataJpaTest`,以真实反映生产环境。
- 通过日志断言 SQL 效率:将 `logging.level.org.hibernate.SQL` 设置为 `DEBUG`,将 `logging.level.org.hibernate.orm.jdbc.bind` 设置为 `TRACE` 以查看参数值。

**注意**:保持实体轻量化,确保查询意图明确,并缩短事务时长。通过抓取策略(Fetch Strategy)和投影(Projection)防止 N+1 问题,并为读/写路径创建索引。

Related Skills

swiftui-patterns

351
from xu-xiang/everything-claude-code-zh

SwiftUI 架构模式,使用 @Observable 进行状态管理,视图组合,导航,性能优化,以及现代 iOS/macOS UI 最佳实践。

docker-patterns

351
from xu-xiang/everything-claude-code-zh

用于本地开发的Docker和Docker Compose模式,包括容器安全、网络、卷策略和多服务编排。

deployment-patterns

351
from xu-xiang/everything-claude-code-zh

部署工作流、CI/CD流水线模式、Docker容器化、健康检查、回滚策略以及Web应用程序的生产就绪检查清单。

springboot-patterns

351
from xu-xiang/everything-claude-code-zh

Spring Boot 架构模式、REST API 设计、分层服务、数据访问、缓存、异步处理与日志。适用于 Java Spring Boot 后端开发。

python-patterns

351
from xu-xiang/everything-claude-code-zh

Pythonic 惯用法、PEP 8 标准、类型提示,以及构建稳健、高效且可维护 Python 应用的最佳实践。

postgres-patterns

351
from xu-xiang/everything-claude-code-zh

PostgreSQL 数据库模式,涵盖查询优化、架构设计、索引和安全。基于 Supabase 最佳实践。

golang-patterns

351
from xu-xiang/everything-claude-code-zh

构建健壮、高效且可维护 Go 应用程序的惯用法(Idiomatic Go)、最佳实践与规范。

django-patterns

351
from xu-xiang/everything-claude-code-zh

Django 架构模式、使用 DRF 的 REST API 设计、ORM 最佳实践、缓存、信号(Signals)、中间件(Middleware)以及生产级 Django 应用。

frontend-patterns

351
from xu-xiang/everything-claude-code-zh

React、Next.js、状态管理(State Management)、性能优化(Performance Optimization)及 UI 最佳实践的前端开发模式。

backend-patterns

351
from xu-xiang/everything-claude-code-zh

后端架构模式、API 设计、数据库优化以及适用于 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

plankton-code-quality

351
from xu-xiang/everything-claude-code-zh

使用 Plankton 实现编写时代码质量强制执行 —— 通过钩子在每次文件编辑时进行自动格式化、代码检查,并由 Claude 驱动自动修复。

autonomous-loops

351
from xu-xiang/everything-claude-code-zh

自主运行 Claude Code 循环的模式与架构 —— 从简单的顺序流水线到 RFC 驱动的多智能体 DAG 系统。