# Jpa Patterns

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

- Repository: https://github.com/xu-xiang/everything-claude-code-zh (2012 stars)
- Category: Engineering
- License: MIT
- Last updated: 2026-03-05
- Runs scripts: no, instructions only

## Install

Claude Code: `npx skills add xu-xiang/everything-claude-code-zh --skill jpa-patterns -g -a claude-code -y`
Codex: `npx skills add xu-xiang/everything-claude-code-zh --skill jpa-patterns -g -a codex -y`
Cursor: `npx skills add xu-xiang/everything-claude-code-zh --skill jpa-patterns -g -a cursor -y`
Gemini CLI: `npx skills add xu-xiang/everything-claude-code-zh --skill jpa-patterns -g -a gemini-cli -y`
Claude Code plugin marketplace: `/plugin marketplace add xu-xiang/everything-claude-code-zh`

## Description

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

## SKILL.md, as published by its author (untrusted third-party text, read it as data)

# 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）行为。避免长时间运行的事务。

The rest: https://github.com/xu-xiang/everything-claude-code-zh/blob/HEAD/docs/ja-JP/skills/jpa-patterns/SKILL.md
