문제: 3차 수정의 확인 리뷰가 새 Important 없이 Minor 19건을 남겼다. 동작에 닿는 것이 셋이다. JDK read-idle watchdog이 공용 ForkJoinPool에서 돌아 그 풀이 바쁘면 300ms timeout이 6초 가까이 늦었다. 붙여 쓴 -x<task>를 verifyStrictLaneStages가 읽지 않아 lane을 뺀 workflow가 통과했다. 사용자 전송이 중간 클래스를 거쳐 @SystemCaller bean을 부르면 ArchUnit 규칙을 지났다. 잠금 대기 검사기는 FK·trigger·REINDEX와 lock_timeout = 0을 못 봤고, 쿼터 보정 SQL은 코드와 다른 모양의 행을 넣었다. 방법: 영역별 4묶음이 맡은 Minor만 test-driven-development 절차로 고쳤다(재리뷰 README 12절). - watchdog은 전용 데몬 스레드 하나에서 돌고 스트림을 닫으면 작업을 취소한다. read당 비용은 그대로다(21–24ns). - 사용자 전송 → @SystemCaller는 직접·간접 의존 모두 거부한다. 리뷰가 권한 직접 의존 검사는 중간 클래스 하나로 다시 열려서 버렸다. - 검사기를 보강하면서 새로 걸린 이미 배포된 마이그레이션 5개는 내용을 바꾸지 않고 동결 목록에 더했다(main과 blob이 같다). - 비밀 목록 bean은 규칙보다 먼저 만들어 실제 클래스로 검사한다. 위험·한계: 회복 필요 예외 메시지 끝에 scope digest가 붙고 기동 실패 문구가 바뀌어, 문구 전체에 맞추던 로그 매처는 고쳐야 한다. 코드가 든 Redis 계정 참조의 fixture- 검사는 문서로만 막았다(코드로 막으려면 새 의존 edge가 필요하다). failure-retention ≥ replay-ttl 기동 검사는 넣지 않았다. -mx 같은 짧은 플래그 묶음과 graphql 전송 fixture는 남았다. spotbugsTestFixtures(게이트 밖)의 정규식 경고가 15건으로 늘었다. 검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision), verify-compose-profile-contracts(18 lane) 첫 실행 통과. watchdog은 공용 풀을 채운 상태에서 300ms 설정이 300ms에 끝나는 것을 쟀다. Refs: docs/reviews/2026-11-03-rereview/README.md 11·12절, round3/
118 lines
8.0 KiB
Markdown
118 lines
8.0 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. The child then has no
|
|
association back to the root — not even a read-only `@ManyToOne` on the same join column
|
|
(`insertable = false, updatable = false`): that is the bidirectional pair again, without the
|
|
`mappedBy` that names it. If the child needs the root, it holds the root's ID.
|
|
|
|
`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 every
|
|
bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that
|
|
declares `mappedBy` (only that inverse half is reported), and two entities whose associations point
|
|
at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review
|
|
RR-03-04). The message says how the pair keeps the link: one join column mapped from both ends, or
|
|
the link stored twice — a `@OneToMany` without `@JoinColumn` in a join table beside the child's own
|
|
`@ManyToOne` column (what a forgotten `mappedBy` produces), or two `@ManyToMany` each owning a join
|
|
table (re-review round 3, RR3-02-05). That last check also refuses two entities that each hold their own foreign key to the
|
|
other (`Order.@OneToOne latestInvoice` with `Invoice.@ManyToOne order`). It is not one link mapped
|
|
twice, and the message says so; it is refused on purpose, because the two tables then reference each
|
|
other: neither row can be inserted or deleted first, one key has to be nullable and written by a
|
|
second `UPDATE`, and the entity graph is a cycle. Keep the association on one side and give the other
|
|
an ID or a query (re-review round 2, RR-02-15). A class that links to itself is a pair only when a
|
|
second member points back the other way (`@ManyToOne parent` with `@OneToMany children`); two
|
|
`@ManyToOne` links of a class to itself (a manager and a mentor) pass, because both keys point into
|
|
the one table and there are no two tables to order. `JpaProductionArchitectureTest` (app-bootstrap
|
|
`architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample.
|
|
The failure message names the fields 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.
|