JPA/Hibernate 模式¶
用于 Spring Boot 中的数据建模、仓库和性能调优。
实体设计¶
@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;
}
启用审计:
关系与 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);
}
- 轻量查询使用投影:
事务¶
- 在服务方法上添加
@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 处理,添加以下配置:
缓存¶
- 一级缓存按 EntityManager 隔离。不要在事务之间保留实体
- 对于读取密集型实体,谨慎考虑二级缓存。验证失效策略
迁移¶
- 使用 Flyway 或 Liquibase。生产环境不要依赖 Hibernate 自动 DDL
- 保持迁移幂等且增量。不要在没有计划的情况下删除列
数据访问测试¶
- 优先使用基于 Testcontainers 的
@DataJpaTest,以反映生产环境 - 使用日志断言 SQL 效率:对于参数值,设置
logging.level.org.hibernate.SQL=DEBUG和logging.level.org.hibernate.orm.jdbc.bind=TRACE
注意:保持实体轻量,有意设计查询,保持事务短小。通过获取策略和投影防止 N+1,并为读取/写入路径创建索引。
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC