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…