SKILL.md
唯讀
名稱
jpa-patterns
描述
適用於 Spring Boot 中實體設計、關聯性設定、查詢最佳化、交易處理、稽核、索引建立、分頁以及連線池設定的 JPA/Hibernate 模式。
JPA/Hibernate 模式
用於 Spring Boot 中的資料模型化、Repository 設計與效能調優。
時機與時機點
- 設計 JPA 實體(Entity)與資料表對映(Table Mappings)
- 定義關聯性(@OneToMany、@ManyToOne、@ManyToMany)
- 最佳化查詢(預防 N+1 問題、抓取策略、Projection 投影)
- 設定交易(Transactions)、稽核(Auditing)或軟刪除(Soft Deletes)
- 建置分頁、排序或自訂 Repository 方法
- 調優資料庫連線池(HikariCP)或二級快取(Second-Level Caching)
實體設計
@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):
@Configuration
@EnableJpaAuditing
class JpaConfig {}
關聯性與預防 N+1 問題
@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
- 預設使用延遲載入(Lazy Loading);需要時在查詢中使用
JOIN FETCH - 避免在集合上使用
EAGER;讀取路徑請優先使用 DTO Projection
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);
Repository 模式
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 來執行輕量級查詢:
public interface MarketSummary {
Long getId();
String getName();
MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);
交易(Transactions)
- 為 Service 方法加上
@Transactional註解 - 讀取路徑使用
@Transactional(readOnly = true)進行最佳化 - 謹慎選擇傳播行為(Propagation);避免執行時間過長的交易
@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);
如需指標式(Cursor-like)分頁,可在 JPQL 中加入 id > :lastId 並配合排序。
索引與效能
- 為常用過濾條件新增索引(
status、slug、外鍵) - 使用符合查詢模式的組合索引(
status, created_at) - 避免使用
select *;僅投影(Project)需要的欄位 - 透過
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 之中;避免在跨交易運作時保留實體
- 對於高讀取量的實體,請審慎評估二級快取,並驗證快取快失效(Eviction)策略
資料庫變更遷移(Migrations)
- 使用 Flyway 或 Liquibase;切勿在正式環境(Production)依賴 Hibernate 自動產生 DDL
- 保持 Migration 具備等冪性(Idempotent)與增量特性;未經過妥善規劃前避免直接刪除欄位
資料存取測試
- 偏好使用
@DataJpaTest搭配 Testcontainers 以真實反映正式環境 - 透過日誌斷言 SQL 執行效率:設定
logging.level.org.hibernate.SQL=DEBUG以及logging.level.org.hibernate.orm.jdbc.bind=TRACE來檢視參數值
切記:保持實體輕量、查詢目標明確、交易簡短。透過 Fetch 策略與 Projection 防止 N+1 問題,並針對讀取/寫入路徑建立合適的索引。






