0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Hibernateで200万件を安全に読み書きする — StatelessSessionとキーセットページング

0
Last updated at Posted at 2026-07-26

概要

200万件規模のバッチ処理において、通常のJPA/Hibernateの使い方をそのまま適用すると、メモリ肥大化や性能劣化を引き起こします。API層(Controller/Service/Repository)で使う標準的なJPAパターンとは別に、バッチ処理専用に採用したHibernateの実装パターンを整理します。

前提:API層の標準パターンをそのまま使えない理由

通常のAPI開発では EntityManager を使い、Spring Data JPAのRepositoryを通じてエンティティを操作します。この標準的な使い方には以下の特性があります。

  • 読み込んだエンティティを一次キャッシュ(永続化コンテキスト)に保持し続ける
  • Dirty Checkingにより変更を自動検知する
  • 遅延ロード(Lazy Loading)によりリレーションを必要時に取得する

これらは数十〜数百件を扱うAPIリクエストには適していますが、200万件を素朴にループで読み込むと、永続化コンテキストの肥大化により確実にメモリを圧迫します。バッチのRead/Writeは、API層とは別の実装方針で設計する必要があります。

StatelessSessionの採用

読み込み専用かつ大量データを扱う処理では、Hibernateの StatelessSession を使用します。

項目 通常のSession(EntityManager) StatelessSession
一次キャッシュ あり なし(都度DBアクセス、メモリ安定)
自動Dirty Checking あり(比較コストが件数に比例して増大) なし(明示的にupdateを呼び出す)
カスケード・遅延ロード 動作する 動作しない(意図的に使わない設計にする)
用途 通常のCRUD・API層 バルク処理専用
StatelessSession session = entityManagerFactory.unwrap(SessionFactory.class).openStatelessSession();

EntityManagerFactory から SessionFactory にアンラップし、openStatelessSession() で取得します。カスケードや遅延ロードが機能しない前提の実装になるため、リレーション先のデータが必要な場合はJOINしたクエリで一度に取得する設計にします。

キーセットページングの採用

大量データの読み取りには、OFFSETベースのページングではなくキーセット方式を採用しました。

-- 避けたいパターン: OFFSET方式
SELECT * FROM customer_order_detail ORDER BY id OFFSET 1990000 LIMIT 500;

-- 採用したパターン: キーセット方式
SELECT * FROM customer_order_detail WHERE id > :lastId ORDER BY id LIMIT 500;

PostgreSQLを含む多くのRDBMSでは、OFFSETが大きくなるほどスキャンコストが線形に増加します。200万件を処理する場合、後半になるほど処理が遅くなる問題が起こります。WHERE id > :lastId によるキーセット方式であれば、常にインデックスを使った一定コストのアクセスになります。

実装:ItemStreamReaderとしてのキーセットReader

Spring Batchの ItemStreamReader として実装し、ExecutionContext を使ったリスタート対応も組み込みます。

public class OrderDetailKeysetItemReader implements ItemStreamReader<OrderDetailProjection> {

    private static final String LAST_ID_KEY = "orderDetailReader.lastId";
    private static final int PAGE_SIZE = 500;

    private static final String QUERY = """
        SELECT new com.example.ecapi.batch.dto.OrderDetailProjection(
            d.id, d.product.id, d.order.customer.id, d.unitPrice, d.quantity)
        FROM CustomerOrderDetail d
        WHERE d.order.id BETWEEN :minId AND :maxId
          AND d.createdAt BETWEEN :from AND :to
          AND d.id > :lastId
        ORDER BY d.id
        """;

    private final EntityManagerFactory entityManagerFactory;
    private final long minId;
    private final long maxId;
    private final Instant from;
    private final Instant to;

    private StatelessSession session;
    private Deque<OrderDetailProjection> buffer = new ArrayDeque<>();
    private long lastId;

    public OrderDetailKeysetItemReader(
            EntityManagerFactory entityManagerFactory,
            long minId, long maxId, Instant from, Instant to) {
        this.entityManagerFactory = entityManagerFactory;
        this.minId = minId;
        this.maxId = maxId;
        this.from = from;
        this.to = to;
    }

    @Override
    public void open(ExecutionContext executionContext) {
        this.lastId = executionContext.getLong(LAST_ID_KEY, 0L);
        this.session = entityManagerFactory.unwrap(SessionFactory.class).openStatelessSession();
    }

    @Override
    public OrderDetailProjection read() {
        if (buffer.isEmpty()) {
            fetchNextPage();
        }
        return buffer.poll();
    }

    private void fetchNextPage() {
        List<OrderDetailProjection> page = session.createQuery(QUERY, OrderDetailProjection.class)
                .setParameter("minId", minId)
                .setParameter("maxId", maxId)
                .setParameter("from", from)
                .setParameter("to", to)
                .setParameter("lastId", lastId)
                .setMaxResults(PAGE_SIZE)
                .list();
        buffer.addAll(page);
        if (!page.isEmpty()) {
            lastId = page.get(page.size() - 1).id();
        }
    }

    @Override
    public void update(ExecutionContext executionContext) {
        executionContext.putLong(LAST_ID_KEY, lastId);
    }

    @Override
    public void close() {
        if (session != null) {
            session.close();
        }
    }
}

このReaderは前回の記事で扱った ExecutionContext の仕組み(open()/update())に則っており、chunkコミットのたびに lastId が保存されます。リスタート時は保存された lastId から再開されるため、既に処理済みの範囲が再読込されることはありません。

minId/maxId はパーティションごとのID範囲、from/to は対象日の範囲です。パーティション分割とキーセットページングを組み合わせることで、各Workerが担当範囲内だけをスキャンする設計になっています。

N+1回避のためのDTOマッピング

集計処理でエンティティのリレーションを辿ると、200万件規模ではN+1問題が致命的になります。

// 避けたいパターン: エンティティを取得してからリレーションを辿る
List<CustomerOrderDetail> details = repository.findByOrderIdBetween(minId, maxId);
for (CustomerOrderDetail detail : details) {
    Product product = detail.getProduct(); // 遅延ロードでN回クエリが発行される
}

SELECT NEW によるコンストラクタ式でDTOに直接マッピングすることで、この問題を回避します。

public record OrderDetailProjection(
        Long id, Long productId, Long customerId, BigDecimal unitPrice, int quantity) {}
SELECT new com.example.ecapi.batch.dto.OrderDetailProjection(
    d.id, d.product.id, d.order.customer.id, d.unitPrice, d.quantity)
FROM CustomerOrderDetail d
WHERE ...

d.product.id や d.order.customer.id はエンティティ全体を読み込むのではなく、Hibernateが必要な列だけをJOINして取得するSQLを生成します。
エンティティのハイドレーション(監査カラムやリレーションの初期化)を伴わないため、200万件規模ではオブジェクト生成コストの差が無視できません。

JDBCバッチ設定

chunk(500) によるコミット単位の制御とは別に、Hibernate/JDBCレベルのバッチ設定も行います。

spring:
  jpa:
    properties:
      hibernate:
        jdbc:
          batch_size: 50
        order_inserts: true
        order_updates: true

chunk(500) が「何件処理したらトランザクションをコミットするか」を決めるビジネス処理の単位であるのに対し、hibernate.jdbc.batch_size は「1回のJDBCラウンドトリップで何件のSQL文をまとめて送るか」というJDBC通信の最適化です。この2つは別のレイヤーの設定であり、片方だけでは効果が出ません。

order_inserts / order_updates を true にしない場合、異なるエンティティ種別のINSERT/UPDATEが交互に発生した際にJDBCバッチが分断され、batch_size の効果が実質的に得られなくなります。

UPSERTはJPAで表現できない

「あれば更新、なければ挿入」というUPSERTは、JPAの save() ではネイティブに表現できません。
merge() はID指定があれば更新扱いになりますが、集計値の加算・上書きといった条件付き更新には対応していません。

この制約から、Writer部分は素のJDBC(JdbcBatchItemWriter + NamedParameterJdbcTemplate)で実装しています。

@Bean
@StepScope
public JdbcBatchItemWriter<SalesSummaryRow> salesSummaryWriter(DataSource dataSource) {
    return new JdbcBatchItemWriterBuilder<SalesSummaryRow>()
            .dataSource(dataSource)
            .sql("""
                INSERT INTO daily_sales_summary_staging
                    (job_execution_id, product_id, sales_date, amount, quantity)
                VALUES (:jobExecutionId, :productId, :salesDate, :amount, :quantity)
                """)
            .itemSqlParameterSourceProvider(row -> {
                var params = new MapSqlParameterSource();
                params.addValue("jobExecutionId", row.jobExecutionId());
                params.addValue("productId", row.productId());
                params.addValue("salesDate", row.salesDate());
                params.addValue("amount", row.amount());
                params.addValue("quantity", row.quantity());
                return params;
            })
            .build();
}

エンティティ経由の書き込みではないため、JPA Auditing(AuditorAware)は機能しません。
created_by/updated_by に相当する値が必要な場合は、バッチ専用のシステムユーザーIDを明示的にパラメータへ含めます。

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class BatchAuditConfig {

    public static final long BATCH_SYSTEM_USER_ID = 0L;

    @Bean
    public AuditorAware<Long> auditorAware() {
        return () -> Optional.of(BATCH_SYSTEM_USER_ID);
    }
}

API側の AuditorAware(SecurityContextHolder から取得)とは別に、バッチ専用の固定値を返す実装を用意しています。
バッチにはHTTPセッションもSpring Securityの認証情報も存在しないため、この分離が必要です。

まとめ

項目 採用方針 理由
セッション StatelessSession 永続化コンテキスト肥大化・Dirty Checkingコストの回避
ページング キーセット方式 OFFSETによるスキャンコスト増大の回避
リレーション取得 SELECT NEW によるDTOマッピング N+1問題の回避、オブジェクト生成コストの削減
JDBCバッチ batch_size + order_inserts/order_updates JDBCラウンドトリップの削減
UPSERT 素のJDBC(JdbcBatchItemWriter) JPAの save() では条件付き更新を表現できないため
監査カラム バッチ専用の固定AuditorAware HTTPセッション・Security Contextが存在しないため

これらはすべて「API層の標準パターンをそのまま持ち込まない」という前提に基づいています。
バッチ処理はAPI開発とは別の制約下にあることを踏まえた実装方針が必要です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?