Files
clean-architecture-backend-…/docs/jpa/batch-write-guide.md
T

65 lines
2.6 KiB
Markdown

# JPA batch write configuration
`HibernateJpaBatchExecutor` is an advanced opt-in. The template does not enable Hibernate batch
write settings globally because statistics and statement reordering add runtime cost even in
applications that never perform bulk writes.
## What the executor owns
A `JpaBatchProfile` owns the JDBC batch size for one batch run. Before the first item is written,
the executor applies `profile.jdbcBatchSize()` to the current Hibernate `Session`. The previous
Session value is restored in `finally`, including failed runs.
The executor does **not** open a transaction. The application service must enter a
`TransactionPort.inWrite(...)` boundary first.
## What the application must configure
If a profile requests insert or update ordering, the matching Hibernate setting must already be
enabled on the SessionFactory:
```yaml
spring:
jpa:
properties:
hibernate:
order_inserts: true
order_updates: true
generate_statistics: true
```
`hibernate.generate_statistics=true` is required because `BatchExecutionResult` reports measured
flush and prepared-statement deltas. A disabled statistics registry would turn those values into
convincing zeros.
The `HibernateStatisticsCollector` must also receive an instrumented `JdbcBatchCounter`.
`HibernateStatisticsCollector.of(sessionFactory)` is intentionally insufficient for this executor:
Hibernate statistics do not expose actual JDBC batch executions.
`hibernate.default_batch_fetch_size` is unrelated to this write executor. It affects association
fetching and belongs to query/fetch tuning instead.
## Entity identifier constraint
When `JpaBatchProfile.batchingRequired()` is true, an entity using
`GenerationType.IDENTITY` is rejected by `HibernateBatchConfigurationGuard`. Hibernate must issue
each INSERT immediately to obtain the generated identifier, so JDBC insert batching cannot satisfy
that profile.
Prefer a sequence-based identifier when a workload requires insert batching. Keep the sequence
allocation size aligned with the database migration.
## Failure behavior
Configuration is checked before the persister receives the first item:
- missing `hibernate.order_inserts=true` when the profile requests insert ordering: fail;
- missing `hibernate.order_updates=true` when the profile requests update ordering: fail;
- disabled Hibernate statistics: fail;
- missing JDBC batch instrumentation: fail;
- no caller-owned transaction: fail.
These failures are deliberate. A batch API that silently degrades to one statement per row produces
correct data but false performance evidence, which is harder to detect than a startup or invocation
failure.