# 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` 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.