Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。
View on GitHubxu-xiang/everything-claude-code-zh
everything-claude-code
February 5, 2026
Select agents to install to:
npx add-skill https://github.com/xu-xiang/everything-claude-code-zh/blob/main/skills/jpa-patterns/SKILL.md -a claude-code --skill jpa-patternsInstallation paths:
.claude/skills/jpa-patterns/# JPA/Hibernate 模式
用于 Spring Boot 中的数据建模、存储层(Repositories)开发和性能调优。
## 实体设计(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 投影(Projections)
```java
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);
```
## 存储层模式(Repository Patterns)
```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);
}
```
- 使用投影(Projections)进行轻量级查询:
```java
public interface MarketSummary {
Long getId();
String getName();
MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);
```
## 事务(Transactions)
- 使用 `@Transactional` 注解 Service 方法
- 在读取路径上使用 `@Transactional(readOnly = true)` 进行优化
- 谨慎选择传播行为(Propagation);避免长事务
```java
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
MarketEntity entity = repo.findBy