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;
}
監査を有効化:
@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);