Skip to content
cccskills
FreePublished on GitHub

jpa-patterns

Spring BootにおけるJPA/Hibernateパターン — エンティティ設計、リレーションシップ、クエリ最適化、トランザクション、監査、インデックス、ページネーション、コネクションプーリング。

The English summary is being prepared. Showing the original description.

See how to install

Files included (1)

  • SKILL.md5.4 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

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を防止し、読み取り/書き込みパスに合わせてインデックスを設定。

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

コーディングエージェント(Claude Code、Aider、Codexなど)のカスタムタスクによる直接比較。合格率、コスト、時間、一貫性メトリクスを測定

The English summary is being prepared. Showing the original description.

hage-oyaji/everything-claude-code-jp-local3Updated Mar 29, 2026

AIエージェントのアクションスペース、ツール定義、オブザベーションフォーマットを設計・最適化し、タスク完了率を向上させる

The English summary is being prepared. Showing the original description.

hage-oyaji/everything-claude-code-jp-local3Updated Mar 29, 2026

評価ファーストの実行、分解、コスト考慮型モデルルーティングによるエージェンティックエンジニアとしての運用

The English summary is being prepared. Showing the original description.

hage-oyaji/everything-claude-code-jp-local3Updated Mar 29, 2026

AIエージェントが実装出力の大部分を生成するチームのためのエンジニアリング運用モデル

The English summary is being prepared. Showing the original description.

hage-oyaji/everything-claude-code-jp-local3Updated Mar 29, 2026

AI支援開発のためのリグレッションテスト戦略。データベース依存なしのサンドボックスモードAPIテスト、自動バグチェックワークフロー、同一モデルがコードの作成とレビューを行う際のAIの盲点を検出するパターン。

The English summary is being prepared. Showing the original description.

hage-oyaji/everything-claude-code-jp-local3Updated Mar 29, 2026

AndroidおよびKotlin Multiplatformプロジェクトのためのクリーンアーキテクチャパターン — モジュール構成、依存関係ルール、UseCase、Repository、データレイヤーパターン

The English summary is being prepared. Showing the original description.

hage-oyaji/everything-claude-code-jp-local3Updated Mar 29, 2026

See all skills by hage-oyaji

Report a problem with this skill