문제: 2026-11-01 성숙도 리뷰에서 High 21건·P1 25건이 나왔다. 결과를 모르는 일을 "확실함"으로 기록했다(발송 중 죽은 알림 재발송, 커밋 중 끊긴 쓰기를 재시도 가능으로 응답, 재시도 가능한 거부를 DEAD로). 중복을 DB가 아니라 코드 순서로 막았다(정산 job, 포스터 제목). 짝 프론트와 wire 계약이 달랐고(처리 중 409, Envelope null), JWT audience 검증이 기본으로 꺼져 있었고, 트레이스가 나가지 않았고, CI가 strict lane 14개를 한 번도 돌리지 않았다. 방법: 발견마다 실패하는 테스트를 먼저 쓰고 고쳤다. 주요 선택: - 알림 attempt는 처음부터 "시작 여부 모름"으로 쓴다(호출 직전 갱신은 쓰기가 하나 늘어 버림). - 정산 job claim은 lease·fence를 갱신하는 UPDATE 한 문장(처리 전체를 트랜잭션으로 감싸는 안은 외부 호출 동안 잠금을 잡아 버림). - 커밋 단계 연결 끊김은 DB_COMPLETION_UNKNOWN(재시도 불가). - 처리 중 409는 retryable=true + Retry-After: 2, Envelope null 필드는 web Jackson mixin으로 생략(shared-contract는 stdlib only). - 트레이싱은 자체 Tracer를 지우고 Boot 4 tracing·OTLP로. - strict lane을 단계에 연결하고 verifyStrictLaneStages가 고아를 막는다. 발견별 RED·GREEN·버린 대안은 리뷰 README 13절 표에 있다. 위험·한계: JWT 모드는 APP_SECURITY_JWT_AUDIENCE가 없으면 기동하지 않는다. 짝 프론트는 409 retryable과 Envelope 키 규칙을 맞춰야 한다. 이 커밋 시점에는 MinIO 공식 이미지가 사라져 MinIO 2 lane이 실패한다 (다음 커밋에서 대체 이미지로 해결). 검증: ci 통과. mainCheck·integrationCheck는 MinIO 2 lane만 실패(이미지 pull 거부). -p optional-platforms ci integrationCheck, performanceCheck, releaseCheck(-PgitRevision) 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 2·13절 BREAKING CHANGE: JWT 모드에서 APP_SECURITY_JWT_AUDIENCE가 필수가 되고 role은 audience client와 realm 것만 읽는다. IDEMPOTENT_IN_FLIGHT가 retryable=true, Retry-After: 2로 바뀌고 Envelope는 null 필드를 보내지 않는다.
102 lines
6.4 KiB
Markdown
102 lines
6.4 KiB
Markdown
# Entity Mapping Guide
|
|
|
|
Design §10-§13. The rules here exist because each one has a failure mode that is invisible in review
|
|
and expensive in production.
|
|
|
|
## The domain owns the model
|
|
|
|
The platform defines no business entity. Table names, column semantics, keys, unique and check
|
|
requirements, associations, cascade rules, lock policy, and soft-delete policy all belong to the
|
|
domain module. There is no `GenericRepository<T, ID>` and no platform base repository, because a
|
|
single generic API forces every aggregate through the same operations — and one aggregate's later
|
|
requirement then changes behaviour for all of them.
|
|
|
|
## Entities must be proxyable
|
|
|
|
- Not `final`. Hibernate creates a lazy proxy by generating a subclass; a final entity cannot be
|
|
subclassed, so *every* association to it loads eagerly whatever the mapping says. Nothing errors.
|
|
- A non-private no-arg constructor. The provider instantiates entities reflectively before
|
|
populating fields.
|
|
|
|
`EntityMappingCondition` in the testkit enforces both.
|
|
|
|
## Identifiers
|
|
|
|
Default to a sequence with an `allocationSize` that matches the migration's `INCREMENT BY`. When
|
|
they disagree, the provider hands out identifiers the sequence has not reserved and the collision
|
|
surfaces later as a primary-key violation under load.
|
|
|
|
`GenerationType.IDENTITY` is supported and limited: the key is assigned on insert, so the provider
|
|
must execute each insert immediately to learn it, which disables JDBC insert batching entirely.
|
|
`HibernateBatchConfigurationGuard` fails a batch profile that targets an IDENTITY entity rather than
|
|
letting the import silently run an order of magnitude slower.
|
|
|
|
UUIDv7 (`UuidV7Generator`) is the application-side option. It is preferred over UUIDv4 for a primary
|
|
key because v4 is uniformly random: every insert lands on a random leaf of the B-tree, so the index
|
|
never stays in cache and write amplification grows with the table.
|
|
|
|
## Values
|
|
|
|
- Enums are `EnumType.STRING` or an explicit converter. **Never** `ORDINAL` — it stores the
|
|
constant's position, so inserting a new constant anywhere but the end silently reinterprets every
|
|
existing row.
|
|
- Money is `BigDecimal` with explicit precision and scale. `double` cannot represent `0.1`, so sums
|
|
drift and reconciliation disagrees with the ledger.
|
|
- `Duration` goes through a converter that stores milliseconds. The ISO-8601 text form sorts and
|
|
compares wrongly in SQL.
|
|
- `Instant` and `OffsetDateTime` map differently; a column typed for one cannot faithfully store the
|
|
other.
|
|
|
|
## Associations
|
|
|
|
Map each association from **one side only**. A JPA association between two entities is one foreign
|
|
key column. A bidirectional pair (`@ManyToOne` on the child plus `@OneToMany(mappedBy = ...)` on
|
|
the parent) stores that one column in two Java fields, and JPA writes only the owning one. The pair
|
|
stays consistent only while every caller remembers to update both fields, and nothing fails when
|
|
someone forgets.
|
|
|
|
What to use, in order of preference:
|
|
|
|
1. **An ID reference between aggregates.** Hold the other aggregate's identifier as a plain column
|
|
(`UUID ownerId`). This is what every production entity in the template does today. Loading the
|
|
other aggregate is an explicit repository call, so a cross-aggregate load is visible in the code.
|
|
2. **A unidirectional `@ManyToOne` inside one aggregate**, always `fetch = FetchType.LAZY`. JPA's
|
|
default for a to-one association is `EAGER`, so every query that loads a child also queries for
|
|
its parent — the most common accidental N+1 in a JPA application.
|
|
3. **A collection is a query, not a field.** "The children of X" is a repository method
|
|
(`findByParentId`, or a fetch-join or projection query that pages in SQL). The query states its
|
|
own fetch plan and page, where a mapped collection hides both.
|
|
4. **Values the aggregate owns** — a list of tags, a set of codes — are `@ElementCollection`
|
|
(`LAZY`), not entities.
|
|
|
|
A unidirectional `@OneToMany` with its own `@JoinColumn` is the exception, not the default. Use it
|
|
only for child entities the root genuinely owns and changes only through itself (the testkit's
|
|
`LifecycleParent` and `PagedParent` are this shape). It still costs an `UPDATE` per child when the
|
|
join column is nullable, and the collection still loads as a unit.
|
|
|
|
`CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns.
|
|
Between independent aggregates it deletes rows another part of the system still owns — another
|
|
reason those are ID references.
|
|
|
|
`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on any
|
|
`@OneToMany`, `@OneToOne` or `@ManyToMany` that declares `mappedBy`, on `@Entity`,
|
|
`@MappedSuperclass` and `@Embeddable` types. `JpaProductionArchitectureTest` (app-bootstrap
|
|
`architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample.
|
|
The failure message names the field and these alternatives.
|
|
|
|
Chosen and rejected:
|
|
|
|
| Option | Decision | Why |
|
|
| --- | --- | --- |
|
|
| One side only (ID reference, unidirectional `@ManyToOne`, collection by query), enforced by ArchUnit | Chosen | The link lives in one field, so there is nothing to keep in step. The rule turns a developer-memory convention into a build failure |
|
|
| Bidirectional with `mappedBy` and an `addChild`/`removeChild` helper that sets both sides | Rejected | The helper is the only thing keeping the two fields in step, and it must be remembered by every caller, every serializer (cycles in `toString`/JSON) and every cascade decision. A missed update leaves a row unlinked or a graph that disagrees with the database, with no error |
|
|
| Ban `@OneToMany` entirely | Rejected for now | It also bans a root-owned child collection, which has no second field to forget. Revisit if a real need for child entities that are read or changed on their own appears — that need is a sign they are a separate aggregate |
|
|
| Document only | Rejected | A convention the build does not check is invisible where the mapping is written, and the next copy of the template inherits whatever the examples show |
|
|
|
|
## Entities never leave the transaction
|
|
|
|
A controller must not return an entity, or a collection or `Optional` of one. Response serialisation
|
|
happens after the transaction closes, so a lazy association touched by the serialiser either throws
|
|
or — with OSIV on, which this platform forbids — issues a query from the view layer, one per element.
|
|
`EntityExposureCondition` checks generic type arguments, not just the erased return type.
|