
关于
JPA/Hibernate 模式,涵盖实体设计、关系映射、查询优化、事务、审计、索引、分页和 Spring Boot 中的连接池。
name: jpa-patterns description: Spring Boot 中 JPA/Hibernate 的实体设计、关系映射、查询优化、事务、审计、索引、分页和连接池模式。 origin: ECC
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,并为你的读写路径建立索引。
兼容工具
Claude CodeCursor
标签
后端开发

