Designing a Mini ORM

Difficulty: Advanced Patterns: Repository, Proxy, Builder Asked at: Amazon, Databricks, Atlassian, Microsoft


Call order.setStatus("PAID") on a plain object and have exactly the right UPDATE reach the database. That is the brief, and an afternoon of work gets you something that appears to satisfy it: a save(Object) that reflects over the fields and writes every column it finds. The interview is about the three requirements that turn that mapper into an ORM, and every one of them is a correctness problem first and a performance problem second.

The first is that loading the same row twice must give you back the same object. A mapper that constructs a fresh instance per query hands two different objects for order 42 to two parts of one request, and the moment one is edited and the other saved, the edit is gone – no exception, no log line, no failing test unless somebody wrote that exact test. The fix is a per-session identity map, and it buys more than deduplication: it is the only reason a graph with references in both directions can be loaded at all.

The second is deciding what SQL to write. “Save everything” is an answer real teams ship, and it is wrong in a way that costs money: it overwrites columns the caller never touched, quietly destroying a concurrent writer’s change. So the session has to know which fields actually changed, and then the writes have to leave in an order the foreign keys accept, which is not the order the caller happened to call save in.

The third is laziness. order.getCustomer() cannot eagerly drag half the database into memory, so it returns something that fetches on first use. That something is a Proxy, and it sends you a bill: a loop over two hundred orders each touching getCustomer() runs two hundred and one queries where two would do, and nothing in the method signature hints that a database is involved.

💡 Identity map = a per-session cache keyed by class and primary key, so the first load of a row constructs the object and every later load of that row returns the identical instance. Learn more →

💡 Unit of Work = one object collecting every pending insert, update and delete in a request and writing them in a single transaction, so either the whole set lands or none does. Learn more →

💡 Lazy loading = deferring a relation’s query until something reads it. Learn more →


Functional Requirements

  1. Mapping metadata – annotations on a plain class declare its table, columns, id, version and relations, and nothing in the entity imports a database driver.
  2. Load by id – session.find(Order.class, 42) returns a usable object, and a second call for the same id in the same session returns the same instance without touching the database.
  3. Change tracking – the session detects which fields changed since load and writes an UPDATE naming only those columns.
  4. Unit of Work – inserts, updates and deletes accumulate and leave in one ordered flush inside one transaction, with commit and rollback.
  5. Lazy relations – a to-one or to-many relation is a proxy that queries on first access, with a batch hook so a loop does not become one query per element.
  6. Typed repositories and optimistic concurrency – a Repository per entity exposes finders and a query builder emitting parameterised SQL, never concatenated values; and an entity with a @Version column fails loudly when somebody else wrote the row first.

Non-Functional Requirements

  1. Reflection happens once per class, not once per row – the EntityMeta for a class is read from its annotations on first use and cached in a ConcurrentHashMap forever. Hydrating a row is then field writes through resolved Field handles: O(columns), no annotation lookup in the loop. Reflecting per row is the easy way to make an ORM slow.
  2. A second load of a loaded id is O(1) and issues no statement – the identity map turns repeat loads into a nested hash lookup, and flush is O(changed fields) in the statements it emits, not O(loaded entities).
  3. One commit applies every pending change or none – a flush that fails part way leaves nothing applied, because it runs inside one transaction and the failure path rolls it back.
  4. A session is single-threaded by contract – the identity map, the snapshots and the pending sets are plain HashMap and LinkedHashSet, guarded by confinement rather than locks. The only structure shared across threads is the metadata cache.

Core Entities

Entity Description
Table Column Id Version ManyToOne OneToMany The mapping annotations. Retained at runtime, read once, then never consulted again
ColumnMeta and EntityMeta One mapped field and one mapped class: column names, resolved Field handles, the id, the version and the relations
MetaCache The ConcurrentHashMap making reflection a one-time cost per class
EntityKey and EntityState The identity map’s key, stable for the object’s managed life, and the TRANSIENT, MANAGED, REMOVED enum
Session and UnitOfWork The identity map, the snapshots and the dirty-field diff; and the pending sets, the topological order and the ordered flush
Repository and Query A typed collection over one entity, and the builder turning a filter into parameterised SQL
LazyRef LazyList BatchQueue SqlExecutor The virtual proxies for a to-one and a to-many relation, the batching hook they resolve through, and the interface that runs statements and counts them

💡 Hydrate = fill a newly constructed object from a result row. The interesting part is the order: it is registered in the identity map before its relations are touched.