docs(jpa): JPA 운영 문서를 한국어로 옮기고 코드와 맞춘다
문제: `docs/jpa`의 문서 12개가 영어였고 `security.md`도 영어 절이 남아 있었다.
`repository-adaptation.md`는 Spring Boot 버전과 leaf 개수를 복사했다(number 예외).
번역하며 대조하니 지금 코드와 다른 주장이 여럿 있었다.
고친 것:
- 13개를 번역했다. 코드·명령·경로·표 구조는 그대로다. `support-matrix.md`의 DB 표와
gate 표는 `JpaReleaseRendering`이 읽는 모양(`| PostgreSQL 17 | Stable |`,
`` | `osiv-disabled` | gate | ``)을 그대로 둔다. 절 번호(§1~§5)는 코드가 인용해 그대로다.
- 다른 문서·코드가 영어 절 제목으로 인용하는 곳("Who may change the schema", "Bound the
lock wait", "Concurrent index builds", "An invalid index exists", "Associations")은
한국어 제목 뒤 괄호에 영어를 남겼다.
- 코드에 맞춘 주장:
- support-matrix: 없는 `JpaPlatformAutoConfiguration.capabilities()` →
`JpaPlatformReport.platformCapabilities()`. COPY 수준은 보고대로 Advanced.
- repository-adaptation: leaf 개수·Boot 버전 → registry와 `libs.versions.toml`,
`src/testkit` → `src/testFixtures`, outbox relay `app-bootstrap` →
`composition:outbox-relay`, 「build-logic이 없다」 → `src/build-logic` convention
plugin, 없는 `runtime_memberships`, 없는 `JpaDataSourceSettings`, 여러 major 선택은
`JpaPlatformContractSupport.start()`가 거부한다(`StablePostgreSqlMatrixContractTest`만
여러 개를 받는다), 이미지는 `container-images.properties`의 digest.
- experimental-promotion-checklist: 결과 이름은 지운 gate의 것임을 밝혔다.
- 테스트: `JpaDocumentationContractTest`가 H2 단락의 「운영 보장이 아니」·「PostgreSQL 계약
증거」와 「알려진 빈틈」을 본다. `PoolLaneClaimTest`는 한국어 금지 문구 셋을 더 본다.
고친 두 테스트의 영어 `@DisplayName`은 AGENTS.md 규칙대로 한국어로 바꿨다.
- 예외 목록에서 JPA language 줄 12개와 number 줄 2개를 지웠다.
버린 대안: H2 단락의 영어 문구를 괄호로 남겨 단언을 그대로 두기. 독자가 읽는 것은
한국어 문장이므로 단언도 그 문장을 붙잡아야 한다.
위험·한계: `PoolLaneClaimTest`의 한국어 금지 문구는 지금 문서를 기준으로 고른 것이라,
다른 말로 쓴 인증 주장은 잡지 못한다. 영어 문구 검사는 그대로 남아 있다.
검증: 최종 트리 기준(첫 커밋 본문 참고).
검증(desktop, 최종 트리 8295db89):
- `:adapter:outbound:persistence-jpa:check` rc=0(666개 실패 0. `JpaDocumentationContractTest` 4,
`JpaReleaseRenderingTest` 13, `PoolLaneClaimTest` 3), `:mainCheck` rc=0, `testQualityCheck` rc=0.
- RED: 기준 커밋의 옛 문서에 대면 `JpaDocumentationContractTest`의 H2 단락·알려진 빈틈 2개가 실패한다.
`PoolLaneClaimTest`는 금지 문구를 더한 것이라 옛 영어 문서에서도 통과한다(RED 없음).
This commit is contained in:
@@ -1,117 +1,92 @@
|
||||
# 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.
|
||||
설계서 §10-§13. 여기 있는 규칙마다, 리뷰에서는 보이지 않고 운영에서는 비싼 실패 꼴이 있다.
|
||||
|
||||
## 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.
|
||||
플랫폼은 업무 엔티티를 정의하지 않는다. 테이블 이름, 열의 뜻, 키, unique·check 요구, 연관, cascade 규칙, lock 정책,
|
||||
soft-delete 정책은 모두 도메인 모듈의 것이다. `GenericRepository<T, ID>`도 플랫폼 base repository도 없다. generic API
|
||||
하나는 모든 aggregate를 같은 연산으로 몰아넣고, 그러면 한 aggregate의 나중 요구가 모두의 동작을 바꾼다.
|
||||
|
||||
## Entities must be proxyable
|
||||
## 엔티티는 proxy가 될 수 있어야 한다
|
||||
|
||||
- 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.
|
||||
- `final`이 아니다. Hibernate는 subclass를 만들어 lazy proxy를 만든다. final 엔티티는 subclass를 만들 수 없으므로 그것으로의
|
||||
연관은 매핑이 뭐라고 하든 *모두* eager로 읽힌다. 아무 오류도 나지 않는다.
|
||||
- private이 아닌 인자 없는 생성자. provider는 칸을 채우기 전에 reflection으로 엔티티를 만든다.
|
||||
|
||||
`EntityMappingCondition` in the testkit enforces both.
|
||||
testkit의 `EntityMappingCondition`이 둘을 강제한다.
|
||||
|
||||
## 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.
|
||||
기본은 sequence이고, `allocationSize`는 마이그레이션의 `INCREMENT BY`와 맞춘다. 둘이 다르면 provider가 sequence가 예약하지
|
||||
않은 식별자를 내주고, 충돌은 나중에 부하에서 primary key 위반으로 드러난다.
|
||||
|
||||
`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.
|
||||
`GenerationType.IDENTITY`는 지원하지만 제한이 있다. 키가 insert 때 정해지므로 provider는 키를 알려고 insert마다 바로
|
||||
실행해야 하고, 그러면 JDBC insert batching이 아예 꺼진다. `HibernateBatchConfigurationGuard`는 IDENTITY 엔티티를 대상으로
|
||||
하는 batch profile을, import가 조용히 열 배 느리게 돌게 두는 대신 실패시킨다.
|
||||
|
||||
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.
|
||||
UUIDv7(`UuidV7Generator`)은 애플리케이션 쪽 선택지다. primary key로는 UUIDv4보다 낫다. v4는 고르게 무작위라서 insert마다
|
||||
B-tree의 무작위 leaf에 떨어지고, 인덱스가 캐시에 머물지 못하며, 쓰기 증폭이 테이블과 함께 커진다.
|
||||
|
||||
## 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.
|
||||
- enum은 `EnumType.STRING`이나 명시적 converter다. `ORDINAL`은 **절대** 쓰지 않는다. 상수의 위치를 저장하므로, 끝이 아닌
|
||||
곳에 새 상수를 넣으면 기존 행이 모두 조용히 다른 뜻이 된다.
|
||||
- 금액은 정밀도와 scale을 명시한 `BigDecimal`이다. `double`은 `0.1`을 나타내지 못해서 합계가 어긋나고 맞추기가 장부와
|
||||
다른 말을 한다.
|
||||
- `Duration`은 밀리초를 저장하는 converter를 거친다. ISO-8601 문자열 꼴은 SQL에서 정렬과 비교가 틀린다.
|
||||
- `Instant`와 `OffsetDateTime`은 다르게 매핑된다. 한쪽에 맞춘 열은 다른 쪽을 그대로 저장하지 못한다.
|
||||
|
||||
## Associations
|
||||
## 연관 (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.
|
||||
연관은 **한쪽에서만** 매핑한다. 두 엔티티 사이의 JPA 연관은 foreign key 열 하나다. 양방향 짝(자식의 `@ManyToOne`과 부모의
|
||||
`@OneToMany(mappedBy = ...)`)은 그 열 하나를 Java 칸 둘에 저장하고, JPA는 소유하는 쪽만 쓴다. 짝은 모든 호출자가 두 칸을
|
||||
함께 고치는 것을 기억할 때만 맞고, 누가 잊어도 아무것도 실패하지 않는다.
|
||||
|
||||
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.
|
||||
1. **aggregate 사이에는 ID 참조.** 다른 aggregate의 식별자를 평범한 열로 든다(`UUID ownerId`). 지금 템플릿의 모든 운영 엔티티가
|
||||
이렇게 한다. 다른 aggregate를 읽는 것은 명시적인 repository 호출이라, aggregate를 넘는 읽기가 코드에 보인다.
|
||||
2. **한 aggregate 안에서는 단방향 `@ManyToOne`**, 늘 `fetch = FetchType.LAZY`. JPA의 to-one 기본값은 `EAGER`라서, 자식을
|
||||
읽는 모든 쿼리가 부모도 조회한다. JPA 애플리케이션에서 가장 흔한 실수 N+1이다.
|
||||
3. **collection은 칸이 아니라 쿼리다.** 「X의 자식들」은 repository 메서드다(`findByParentId`, 또는 SQL에서 페이지를 나누는
|
||||
fetch join이나 projection 쿼리). 쿼리는 자기 fetch 계획과 페이지를 말하고, 매핑한 collection은 둘 다 숨긴다.
|
||||
4. **aggregate가 가진 값**(태그 목록, 코드 집합)은 엔티티가 아니라 `@ElementCollection`(`LAZY`)이다.
|
||||
|
||||
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.
|
||||
자기 `@JoinColumn`이 있는 단방향 `@OneToMany`는 기본이 아니라 예외다. root가 정말 가지고 root를 통해서만 바꾸는 자식
|
||||
엔티티에만 쓴다(testkit의 `LifecycleParent`와 `PagedParent`가 이 모양이다). join 열이 nullable이면 자식마다 `UPDATE` 한
|
||||
번이 들고, collection은 여전히 한 덩어리로 읽힌다. 그러면 자식에는 root로 돌아가는 연관이 없다. 같은 join 열에 읽기 전용
|
||||
`@ManyToOne`(`insertable = false, updatable = false`)도 두지 않는다. 그것은 이름을 붙이는 `mappedBy`만 없을 뿐 다시 양방향
|
||||
짝이다. 자식이 root가 필요하면 root의 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.
|
||||
`orphanRemoval`과 함께 쓰는 `CascadeType.ALL`은 aggregate가 정말 가진 자식에만 맞다. 독립된 aggregate 사이에서는 시스템의
|
||||
다른 부분이 아직 가진 행을 지운다. 그것들이 ID 참조인 또 하나의 이유다.
|
||||
|
||||
`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`)가 운영 그래프 전체에 건다.
|
||||
The failure message names the fields and these alternatives.
|
||||
`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()`(testkit)는 `@Entity`, `@MappedSuperclass`, `@Embeddable` 타입의
|
||||
모든 양방향 짝에서 빌드를 실패시킨다. `mappedBy`를 선언한 연관(그 반대쪽 반만 보고한다), 그리고 `mappedBy` 없이 서로를
|
||||
가리키는 두 엔티티(두 반을 다 보고한다. 위의 `@JoinColumn` 꼴, review RR-03-04)다. 메시지는 짝이 링크를 어떻게 가지는지
|
||||
말한다. 양 끝에서 매핑한 join 열 하나이거나, 링크를 두 번 저장한 것이다. 두 번 저장한 것은 자식 자신의 `@ManyToOne` 열 옆
|
||||
join 테이블의, `@JoinColumn` 없는 `@OneToMany`(`mappedBy`를 잊으면 생긴다)이거나, 저마다 join 테이블을 가진 `@ManyToMany`
|
||||
둘이다(재확인 리뷰 round 3, RR3-02-05). 그 마지막 검사는 서로에게 저마다 foreign key를 든 두 엔티티도 거부한다
|
||||
(`Order.@OneToOne latestInvoice`와 `Invoice.@ManyToOne order`). 링크 하나를 두 번 매핑한 것은 아니고, 메시지도 그렇게
|
||||
말한다. 일부러 거부한다. 그러면 두 테이블이 서로를 참조해서, 어느 행도 먼저 넣거나 지울 수 없고, 키 하나는 nullable이어야
|
||||
하고 두 번째 `UPDATE`로 써야 하며, 엔티티 그래프가 cycle이 된다. 연관은 한쪽에 두고 다른 쪽에는 ID나 쿼리를 준다(재확인
|
||||
리뷰 round 2, RR-02-15). 자기 자신에 링크하는 클래스는, 두 번째 멤버가 반대로 가리킬 때만 짝이다(`@ManyToOne parent`와
|
||||
`@OneToMany children`). 자기 자신으로의 `@ManyToOne` 링크 둘(manager와 mentor)은 통과한다. 두 키가 모두 한 테이블을 가리켜서
|
||||
순서를 정할 두 테이블이 없기 때문이다. 이 규칙은 `JpaProductionArchitectureTest`(app-bootstrap `architectureTest`)가 운영
|
||||
그래프 전체에 건다. 실패 메시지가 칸 이름과 이 대안들을 알려 준다.
|
||||
|
||||
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 |
|
||||
| 한쪽만(ID 참조, 단방향 `@ManyToOne`, 쿼리로 읽는 collection), ArchUnit으로 강제 | 고름 | 링크가 칸 하나에 있어서 맞춰 둘 것이 없다. 규칙이 개발자의 기억에 맡긴 관례를 빌드 실패로 바꾼다 |
|
||||
| `mappedBy`와 양쪽을 다 설정하는 `addChild`/`removeChild` helper를 둔 양방향 | 버림 | 두 칸을 맞춰 두는 것은 helper뿐이고, 모든 호출자, 모든 serializer(`toString`·JSON의 cycle), 모든 cascade 결정이 그것을 기억해야 한다. 고치기를 하나 놓치면 링크 없는 행이나 DB와 다른 그래프가 남고, 오류는 없다 |
|
||||
| `@OneToMany`를 아예 금지 | 지금은 버림 | root가 가진 자식 collection도 막는데, 그것에는 잊을 두 번째 칸이 없다. 자식 엔티티를 따로 읽거나 바꿀 실제 필요가 생기면 다시 본다. 그 필요는 그것이 별도 aggregate라는 신호다 |
|
||||
| 문서만 | 버림 | 빌드가 확인하지 않는 관례는 매핑을 쓰는 자리에서 보이지 않고, 템플릿의 다음 사본은 예시가 보여 주는 것을 그대로 물려받는다 |
|
||||
|
||||
## 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.
|
||||
controller는 엔티티를, 또는 엔티티의 collection이나 `Optional`을 돌려주지 않는다. 응답 직렬화는 트랜잭션이 닫힌 뒤에 일어나므로,
|
||||
serializer가 건드린 lazy 연관은 예외를 던지거나, OSIV가 켜져 있으면(이 플랫폼은 금지한다) view 계층에서 원소마다 쿼리를 낸다.
|
||||
`EntityExposureCondition`은 지워진 반환 타입만이 아니라 generic 타입 인자까지 확인한다.
|
||||
|
||||
Reference in New Issue
Block a user