Skip to content

Latest commit

 

History

History
1674 lines (1358 loc) · 59.8 KB

MONGODB.adoc

File metadata and controls

1674 lines (1358 loc) · 59.8 KB

SmallMind MongoDB

The smallmind-mongodb parent module collects two publishable artifacts that sit on top of the stock MongoDB Java driver (mongodb-driver-sync, mongodb-driver-core, bson):

  • mongodb-utility — five small classes and a single MongoAcknowledgment enum that turn the driver’s builder-heavy configuration surface (MongoClientSettings.builder(), cluster settings, pool settings, SSL context, credential assembly) into a handful of Spring FactoryBean implementations. A running MongoClient comes out the other end as a managed singleton with a destroy() that closes the client during context shutdown.

  • mongodb-throng — a small, annotation-driven object/document mapper built against the driver’s own Codec / CodecRegistry infrastructure. It vends a single ThrongClient whose CRUD surface (count, find, findOne, insert, update, delete) is statically typed over @Entity-annotated Java classes and whose query, projection, sort, and update DSLs are thin fluent wrappers around com.mongodb.client.model.Filters, Projections, Sorts, and Updates.

The two modules are independent — mongodb-throng does not depend on mongodb-utility, and an application can adopt either one alone — but the common deployment shape is to use mongodb-utility to construct the driver MongoClient and then hand that client to a ThrongClient together with the list of @Entity classes it should recognize.

The MongoDB Java driver is a complete, general-purpose API. However, many clients of that service will end up writing the same glue:

  1. Walk a property file or Spring XML of broker hosts, convert them into ServerAddress instances, and feed the resulting array to ClusterSettings.Builder#hosts. For anything more than a single mongo instance, produce that array by hand.

  2. Build a MongoClientSettings by chaining a half-dozen applyToClusterSettings / applyToSocketSettings / applyToConnectionPoolSettings / applyToSslSettings lambdas, each of which mutates a separate builder. Remember which knobs belong to which builder. Remember that WriteConcern attaches to the outer builder, not the cluster one.

  3. Carry a plaintext password into a MongoCredential without leaving a String reference on the heap longer than necessary.

  4. Close the MongoClient during application shutdown so connection pools drain cleanly.

  5. Adopt a convention for turning Java classes into BSON documents — the driver vends a PojoCodecProvider but leaves decisions about id handling, polymorphism, embedded documents, lifecycle callbacks, and index creation to each project.

  6. Resolve indexes separately from mapping — read an annotation or configuration file, build a NewIndex, call createIndexes(List<IndexModel>), and try to keep the two sides in sync when a schema evolves.

  7. Write the dozens of lines of com.mongodb.client.model.Filters and com.mongodb.client.model.Updates incantations that every typed query requires.

smallmind-mongodb assembles (1)–(4) once as mongodb-utility, and (5)–(7) once as mongodb-throng. A caller that needs a working, authenticated, pool-tuned MongoClient plus typed CRUD over its own annotated entities writes this:

MongoClient mongoClient = /* from MongoClientFactoryBean */;
ThrongClient throng = new ThrongClient(
    mongoClient,
    "orders-db",
    new ThrongOptions(false, true, true),
    Order.class, OrderLine.class);

List<Order> open = throng.find(Order.class,
    Query.with().filter(Filter.where("status").eq("OPEN"))
                .sort(Sort.on().desc("placedAt"))
                .limit(50))
    .asList();

…and never touches MongoClientSettings.builder, PojoCodecProvider, IndexModel, or com.mongodb.client.model.Filters directly.

  • mongodb-utility turns Spring XML into a MongoClient:

    • models the cluster as ServerAddress[] produced by a pattern/spread pair (mongo#.internal:27017 + 1-3);

    • builds a single MongoCredential for SCRAM-SHA-1 authentication;

    • assembles a MongoClientSettings from 20+ nullable properties, applying each non-null value to the correct sub-builder and leaving the driver’s defaults where nothing is set;

    • constructs and tears down the MongoClient as a Spring-managed singleton;

    • canonicalizes the five most common write-concern levels as an enum (MongoAcknowledgment) and produces WriteConcern instances with or without journaling via a non-singleton FactoryBean (MongoWriteConcern).

  • mongodb-throng turns annotated Java classes into typed CRUD:

    • discovers mapping from five class-level and field-level annotations (@Entity, @Embedded, @Id, @Property, @Codec) plus a polymorphism declaration (@Polymorphic);

    • wires BSON codecs against the driver’s own CodecRegistry — so every value passed into a filter or update still goes through the registered chain;

    • supports entity lifecycle callbacks (@PrePersist, @PostPersist, @PreLoad, @PostLoad) with strict rules about which are static, which take a BsonDocument, and which are for @Entity classes only;

    • discovers index declarations (@Indexed, @Index, @Indexes, @AllIndexes) on the entity and applies them on ThrongClient construction when createIndexes is on;

    • vends fluent builders for filters (Filter), updates (Updates), projections (Projections), and sorts (Sort), and composes them with paging and batch-size settings through Query;

    • exposes results as a lazy ThrongIterable<T> that decodes each ThrongDocument into a typed entity on demand, firing lifecycle callbacks as it goes.

  • It does not wrap MongoClient or MongoCollection. ThrongClient is a single, non-transactional façade over a MongoDatabase; applications that need transactions or change streams should use the driver MongoClient directly and keep ThrongClient for CRUD and aggregation.

  • It does not own the MongoClient lifecycle from inside ThrongClient. The MongoClient passed in is owned by the caller (typically MongoClientFactoryBean’s `destroy()).

  • It supplies a small aggregation DSL (Pipeline) covering the common pipeline stages ($match, $sort, $project, $skip, $limit, $count, $unwind, $lookup, $group) plus a raw-stage escape hatch. Anything else ($facet, $bucket, $graphLookup, change streams, transactions) is the driver’s job, reached through the raw MongoClient.

  • It does not offer a reactive or async surface. Both modules target the synchronous driver.

  • It does not ship connection-string parsing (MongoClientURI/ConnectionString). The utility module builds a MongoClientSettings from typed components instead.

  • It does not support entity-level polymorphism. @Polymorphic is usable on @Embedded classes only; an @Entity with @Polymorphic fails mapping.

If you are new to the module, read in this order:

If you know the driver and need a fast entry point:

If you are diagnosing a failure:

Artifact Module name Role

mongodb-utility

org.smallmind.mongodb.utility

Spring FactoryBean implementations that build ServerAddress[], MongoCredential, WriteConcern, MongoClientSettings, and a managed MongoClient. Depends on spring-beans as an optional compile dependency.

mongodb-throng

org.smallmind.mongodb.throng

Annotation-driven object/document mapper over the sync driver. Exposes ThrongClient, ThrongOptions, the query. DSL, the mapping.annotation. / lifecycle.annotation. / index.annotation. annotation packs, and the ThrongDocument codec. Optional integration with Jackson (jackson-databind) for JSON ↔ BSON translation in json.JsonUtility.

A few ideas recur throughout the module and are worth naming up front.

Server pattern and spread

The mechanism MongoServerFactoryBean uses to turn one template into a ServerAddress[]. A in the pattern is replaced by each value produced by org.smallmind.nutsnbolts.util.Spread.calculate(serverSpread). mongo.internal:27017 with spread 1-3 yields mongo1.internal:27017, mongo2.internal:27017, mongo3.internal:27017. With no #, the pattern is parsed as a single host (with an explicit :port or the driver’s default 27017).

Acknowledgment level

MongoAcknowledgment is a closed enum of five write-concern choices: ZERO (unacknowledged, not journable), ONE, TWO, THREE, and MAJORITY (all journable). It exists so the Spring XML can use a simple enum literal rather than an org.springframework.util.PropertiesUtil-style constant reference against com.mongodb.WriteConcern. MongoWriteConcern consumes an acknowledgment plus a journaled flag and emits a concrete WriteConcern — calling withJournal(true) only when the chosen level is journable.

Codec registry composition

ThrongClient builds a single CodecRegistry out of three pieces, in this order: (1) the ThrongDocumentCodec for raw ThrongDocument pass-through; (2) the embedded codecs it discovered while scanning @Embedded classes; (3) the database’s own registry wrapped with an ArrayCodecProvider that handles Java array fields. Every filter, update, or value written through the client goes through this merged registry.

Entity vs. embedded

An @Entity is a top-level document that maps to a MongoDB collection. It has exactly one @Id field, may declare lifecycle callbacks, and may declare indexes. An @Embedded class is a nested object with no collection of its own. It may not declare lifecycle callbacks; it may declare @Polymorphic to be discriminated across multiple subtypes; and its indexes, if any, must be declared on the parent entity.

Lazy decoding

ThrongIterable<T> wraps the driver’s FindIterable<ThrongDocument> and decodes each result into a typed entity only when the caller advances the iterator. asList() forces the full decode; iterator traversal decodes one document at a time. Lifecycle callbacks (@PreLoad / @PostLoad) fire at decode time, not at query time.

Filter state machine

A Filter built by Filter.where(field) is incomplete until a comparison method (eq, gt, in, regex, etc.) applies a condition. Calling toBsonDocument on an incomplete filter throws UnsupportedOperationException; calling a second comparison on a closed filter throws IllegalFilterStateException. The rule exists so a typo (where("x").eq(1).eq(2)) fails loudly rather than silently overwriting the first comparison.

Both artifacts are published under org.smallmind. Depend on one, the other, or both.

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>mongodb-utility</artifactId>
  <version>${project.version}</version>
</dependency>

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>mongodb-throng</artifactId>
  <version>${project.version}</version>
</dependency>

Transitively each pulls in the driver artifacts (bson, mongodb-driver-core, mongodb-driver-sync) at the versions declared by the parent POM, plus smallmind-nutsnbolts for shared utilities (pattern spread expansion, generic-type reflection, field accessors, formatted exceptions).

Optional dependencies:

  • mongodb-utility declares spring-beans as optional compile. The Spring FactoryBean classes require it; programmatic use of the enums (MongoAcknowledgment) and plain value objects (MongoServer) does not.

  • mongodb-throng declares tools.jackson.core:jackson-databind as optional. org.smallmind.mongodb.throng.json.JsonUtility only compiles when Jackson is on the classpath.

  • A MongoDB cluster reachable from the application. The utility module builds settings for plain TCP, SSL (with an optional certResource), and SCRAM-SHA-1 authentication. Other authentication mechanisms must be plugged into a caller-supplied MongoCredential.

  • Java reflection access to the @Entity / @Embedded classes' private fields and no-arg constructors. Throng reads and writes fields through FieldUtility.getFieldAccessors, with method handles created from its own MethodHandles.Lookup; there is no Unsafe shortcut.

  • Exactly one version of the MongoDB driver on the classpath. Mixing driver versions across modules is the common source of NoSuchMethodError at client construction.

Both jars ship explicit module descriptors (org.smallmind.mongodb.utility and org.smallmind.mongodb.throng, each exporting every package it contains). On the classpath the descriptors are ignored. The repository-wide rules are in Module Path And Classpath; this section lists what is specific to these two modules.

Required modules. Both require the driver’s automatic modules org.mongodb.bson, org.mongodb.driver.core, and org.mongodb.driver.sync.client, and re-export org.smallmind.nutsnbolts (requires transitive). Driver types such as MongoClient, Bson, and CodecRegistry appear in public signatures of both modules, but automatic modules are never re-exported, so require the driver modules you use in your own descriptor.

Optional modules. mongodb-utility declares requires static spring.beans for its FactoryBean classes. mongodb-throng declares requires static tools.jackson.databind for JsonUtility; Jackson is an explicit module, so if you use JsonUtility on a module path, require tools.jackson.databind yourself or add it with --add-modules.

Packages these modules open. mongodb-utility opens org.smallmind.mongodb.utility.spring to spring.core and spring.beans.

Packages you open. Throng constructs your @Entity and @Embedded classes and the codecs named by @Codec, invokes their lifecycle callbacks, and reads and writes their fields, all with its own access. Open each package holding mapped classes to org.smallmind.mongodb.throng:

module com.example.app {

  requires org.mongodb.bson;
  requires org.mongodb.driver.core;
  requires org.mongodb.driver.sync.client;
  requires org.smallmind.mongodb.throng;

  opens com.example.app.model to org.smallmind.mongodb.throng;
}

Without it, building the class’s codec (in ThrongClient’s constructor) fails with `IllegalAccessException: module com.example.app does not open com.example.app.model to module org.smallmind.mongodb.throng. Throng does not need to read your module; the read edge is added when the codec is built.

The fastest path is: wire a MongoClient through mongodb-utility, instantiate a ThrongClient over it, and call typed CRUD.

<bean id="mongoServers"
      class="org.smallmind.mongodb.utility.spring.MongoServerFactoryBean">
  <property name="serverPattern" value="mongo#.internal:27017"/>  (1)
  <property name="serverSpread"  value="1-3"/>                    (2)
</bean>

<bean id="mongoCredential"
      class="org.smallmind.mongodb.utility.spring.MongoCredentialFactoryBean">
  <property name="user"     value="app-service"/>
  <property name="password" value="${mongo.password}"/>           (3)
  <property name="source"   value="admin"/>                       (4)
</bean>

<bean id="mongoWriteConcern"
      class="org.smallmind.mongodb.utility.spring.MongoWriteConcern">
  <property name="acknowledgment" value="MAJORITY"/>              (5)
  <property name="journaled"      value="true"/>
</bean>

<bean id="mongoClientSettings"
      class="org.smallmind.mongodb.utility.spring.MongoClientSettingsFactoryBean">
  <property name="serverAddresses" ref="mongoServers"/>
  <property name="mongoCredential" ref="mongoCredential"/>
  <property name="writeConcern"    ref="mongoWriteConcern"/>
  <property name="sslEnabled"      value="true"/>
  <property name="connectionPoolMaxSize" value="50"/>
</bean>

<bean id="mongoClient"
      class="org.smallmind.mongodb.utility.spring.MongoClientFactoryBean">
  <property name="clientSettings" ref="mongoClientSettings"/>     (6)
</bean>
  1. Template for the broker host names. # marks the expansion point.

  2. The spread 1-3 produces three addresses on port 27017.

  3. Plain string; the factory converts it to a char[] when it constructs the MongoCredential.

  4. Authentication database. For SCRAM users defined in admin, use admin; for users defined in the application database, use the database name.

  5. An enum literal — ZERO, ONE, TWO, THREE, or MAJORITY. withJournal(true) is applied only for journable levels (everything except ZERO).

  6. MongoClientFactoryBean calls MongoClients.create(settings) eagerly in afterPropertiesSet and calls client.close() in destroy. The surrounding Spring context owns the lifecycle.

import org.bson.types.ObjectId;
import org.smallmind.mongodb.throng.mapping.annotation.Entity;
import org.smallmind.mongodb.throng.mapping.annotation.Id;
import org.smallmind.mongodb.throng.mapping.annotation.Property;

@Entity("orders")                            (1)
public class Order {

  @Id                                         (2)
  private ObjectId id;

  @Property("placed_at")                      (3)
  private long placedAt;

  @Property                                   (4)
  private String status;

  public Order () {}                          (5)

  public ObjectId getId () { return id; }
  public void setId (ObjectId id) { this.id = id; }

  public long getPlacedAt () { return placedAt; }
  public void setPlacedAt (long placedAt) { this.placedAt = placedAt; }

  public String getStatus () { return status; }
  public void setStatus (String status) { this.status = status; }
}
  1. value() on @Entity names the MongoDB collection. The annotation’s polymorphic() member is unused here and must stay at its default @Polymorphic() (empty).

  2. Exactly one @Id field is required. Its default storage name is _id; pass @Id("alternative_id") to override.

  3. A stored field whose BSON name differs from the Java field name.

  4. No-arg @Property uses the Java field name (status) as the BSON name.

  5. Throng constructs entities reflectively with a no-arg constructor. It is required on both @Entity and @Embedded classes.

import org.smallmind.mongodb.throng.ThrongClient;
import org.smallmind.mongodb.throng.ThrongOptions;

ThrongClient throng = new ThrongClient(
    mongoClient,
    "orders-db",
    new ThrongOptions(false, true, true),       (1)
    Order.class);                                (2)
  1. storeNulls=false, createIndexes=true, includeCollation=true.

  2. Entity and embedded classes are registered up front. Any class not listed here produces ThrongRuntimeException("Unmapped entity type(…​)") at the first CRUD call.

import org.smallmind.mongodb.throng.query.Filter;
import org.smallmind.mongodb.throng.query.Query;
import org.smallmind.mongodb.throng.query.Sort;

List<Order> open = throng.find(
    Order.class,
    Query.with()
         .filter(Filter.where("status").eq("OPEN"))
         .sort(Sort.on().desc("placed_at"))          (1)
         .limit(50))
    .asList();                                        (2)
  1. Sort by the BSON field name, not the Java field name. Throng does not translate Java field references in the DSL.

  2. ThrongIterable.asList() eagerly drains the cursor.

A plain value object holding a (host, port) pair, default port 27017. It has a no-arg constructor for bean wiring and a convenience (String, int) constructor. It is not consumed by the MongoServerFactoryBean — which uses pattern/spread expansion to produce ServerAddress[] directly — but is useful in custom wiring that needs to aggregate hosts from multiple sources.

Constant Driver WriteConcern Journable

ZERO

WriteConcern.UNACKNOWLEDGED

no

ONE

WriteConcern.W1

yes

TWO

WriteConcern.W2

yes

THREE

WriteConcern.W3

yes

MAJORITY

WriteConcern.MAJORITY

yes

The enum is the contract for MongoWriteConcern.setAcknowledgment. journable is consulted by MongoWriteConcern before it decides whether to apply withJournal(true).

Spring FactoryBean<ServerAddress[]>. Parses a serverPattern (mongo#.internal:27017 or a plain localhost) and an optional serverSpread (1-3, a-c, 1,2,5) and emits the corresponding array during afterPropertiesSet.

Parsing rules (mirroring the Kafka module’s equivalent):

  • No #, no : — single address, port defaults to 27017.

  • No #, with : — single address, host is the prefix, port is the suffix parsed as int.

  • With #, no : — one address per spread value, port defaults to 27017.

  • With # and : — one address per spread value; the literal port after : applies to every address.

An empty or null serverPattern leaves serverAddresses at null. getObject() is then null — callers that require a non-null result must set the pattern explicitly.

Note

A placed after the first : will be treated as part of the port string and fail with NumberFormatException. Keep the in the host portion.

Spring FactoryBean<MongoCredential>. Produces a single MongoCredential via MongoCredential.createScramSha1Credential(user, source, password.toCharArray()). Every property is required; there are no defaults.

For authentication mechanisms other than SCRAM-SHA-1 (SCRAM-SHA-256, X.509, Kerberos, AWS IAM), construct the MongoCredential directly and inject it into MongoClientSettingsFactoryBean.setMongoCredential.

Spring FactoryBean<WriteConcern> with isSingleton() = false. The contract is:

  • setAcknowledgment(MongoAcknowledgment) selects the level;

  • setJournaled(boolean) asks for journal acknowledgment, but has no effect unless the chosen level is journable.

A journable level plus journaled=true emits acknowledgment.getWriteConcern().withJournal(true); any other combination returns acknowledgment.getWriteConcern() unchanged.

Spring FactoryBean<MongoClientSettings> with 20+ nullable setters. Each non-null property applies to the appropriate sub-builder; every null property leaves the driver’s default in place.

Behavior worth knowing:

  • SSL context — if certResource is set, the factory loads a trust store via org.smallmind.nutsnbolts.security.TrustManagerUtility.load() and installs an SSLContext initialized with that trust manager. If certResource is null, the default JSSE trust store is used.

  • SSL enabled — controlled independently by sslEnabled. SSL is only applied when the flag is true; the trust material is loaded whenever certResource is set, regardless of the flag.

  • Write concern — applied only if writeConcern is non-null and writeConcernEnabled is not explicitly false. This lets an operator disable write-concern overrides without removing the bean reference.

  • UUID representation — hard-coded to UuidRepresentation.STANDARD. There is no property to override it.

  • Codec registry — if codecRegistry is set, it is prepended to the driver defaults via CodecRegistries.fromRegistries(custom, MongoClientSettings.getDefaultCodecRegistry()). The composite wins for types the custom registry covers and falls through for everything else.

The full setter list (all accept the standard boxed types, all apply their value only when non-null):

Setter Type Applied to

codecRegistry

CodecRegistry

client-wide codec registry

certResource

Resource

SSL trust store

mongoCredential

MongoCredential

credential

serverAddresses

ServerAddress[]

ClusterSettings#hosts

readPreference

ReadPreference

client-wide read preference

readConcern

ReadConcern

client-wide read concern

writeConcern

WriteConcern

client-wide write concern

writeConcernEnabled

Boolean

gate for applying writeConcern

retryReads

Boolean

read retry

retryWrites

Boolean

write retry

sslEnabled

Boolean

SslSettings#enabled

allowInvalidHostNames

Boolean

SslSettings#invalidHostNameAllowed

socketConnectTimeoutMilliseconds

Integer

SocketSettings#connectTimeout

serverSelectionTimeoutMilliseconds

Integer

ClusterSettings#serverSelectionTimeout

connectionPoolMinSize

Integer

ConnectionPoolSettings#minSize

connectionPoolMaxSize

Integer

ConnectionPoolSettings#maxSize

connectionPoolMaxConnecting

Integer

ConnectionPoolSettings#maxConnecting

connectionPoolMaxWaitTimeMilliseconds

Integer

ConnectionPoolSettings#maxWaitTime

connectionPoolMaxConnectionLifeTimeSeconds

Integer

ConnectionPoolSettings#maxConnectionLifeTime

connectionPoolMaxConnectionIdleTimeSeconds

Integer

ConnectionPoolSettings#maxConnectionIdleTime

Spring FactoryBean<MongoClient> that also implements InitializingBean and DisposableBean. On context startup it calls MongoClients.create(clientSettings) and holds the resulting MongoClient; on context shutdown it calls client.close().

There is no reconnection, refresh, or reload behavior. Replacing credentials or server lists at runtime requires either refreshing the Spring context that owns the bean or building a new MongoClient outside of Spring.

A representative end-to-end configuration:

<bean id="mongoServers"
      class="org.smallmind.mongodb.utility.spring.MongoServerFactoryBean">
  <property name="serverPattern" value="mongo#.prod.internal:27017"/>
  <property name="serverSpread"  value="1-3"/>
</bean>

<bean id="mongoCredential"
      class="org.smallmind.mongodb.utility.spring.MongoCredentialFactoryBean">
  <property name="user"     value="${mongo.user}"/>
  <property name="password" value="${mongo.password}"/>
  <property name="source"   value="admin"/>
</bean>

<bean id="mongoWriteConcern"
      class="org.smallmind.mongodb.utility.spring.MongoWriteConcern">
  <property name="acknowledgment" value="MAJORITY"/>
  <property name="journaled"      value="true"/>
</bean>

<bean id="mongoClientSettings"
      class="org.smallmind.mongodb.utility.spring.MongoClientSettingsFactoryBean">
  <property name="serverAddresses"                            ref="mongoServers"/>
  <property name="mongoCredential"                            ref="mongoCredential"/>
  <property name="writeConcern"                               ref="mongoWriteConcern"/>
  <property name="readPreference">
    <util:constant static-field="com.mongodb.ReadPreference.SECONDARY_PREFERRED"/>
  </property>
  <property name="sslEnabled"                                 value="true"/>
  <property name="retryWrites"                                value="true"/>
  <property name="retryReads"                                 value="true"/>
  <property name="socketConnectTimeoutMilliseconds"           value="5000"/>
  <property name="serverSelectionTimeoutMilliseconds"         value="15000"/>
  <property name="connectionPoolMinSize"                      value="5"/>
  <property name="connectionPoolMaxSize"                      value="50"/>
  <property name="connectionPoolMaxConnectionLifeTimeSeconds" value="600"/>
</bean>

<bean id="mongoClient"
      class="org.smallmind.mongodb.utility.spring.MongoClientFactoryBean">
  <property name="clientSettings" ref="mongoClientSettings"/>
</bean>

ThrongClient is the entry point for every typed operation. It is constructed once per database, holds no connection state beyond what the underlying driver maintains, and is safe to share across threads.

public ThrongClient(MongoClient mongoClient,
                    String database,
                    ThrongOptions options,
                    Class<?>... entityClasses)
    throws ThrongMappingException, NoSuchMethodException,
           InstantiationException, IllegalAccessException,
           InvocationTargetException;

Construction:

  1. Resolves the MongoDatabase from the MongoClient.

  2. Composes an initial CodecRegistry that prepends an ArrayCodecProvider (respecting options.isStoreNulls()) to the database registry.

  3. Scans entityClasses twice:

    • first pass registers codecs for @Embedded classes (ThrongEmbeddedUtility.generateEmbeddedCodec), producing either a plain ThrongEmbeddedCodec or a ThrongPolymorphicEmbeddedCodec depending on whether the class has @Polymorphic(value = {…​});

    • second pass registers ThrongEntityCodec instances for @Entity classes and, when options.isCreateIndexes() is true, calls IndexUtility.createIndex on the collection with the entity’s compound and single-field indexes.

  4. Builds the final CodecRegistry used by every CRUD call: ThrongDocumentCodec + embedded codecs + driver registry
    ArrayCodecProvider.

CRUD surface:

Method Behavior

long count(Class<T>, Filter)

Counts documents satisfying filter in the entity’s collection.

ThrongIterable<T> find(Class<T>, Query)

Applies the query (filter, sort, projection, skip, limit, batch size) and returns a lazy iterable that decodes each ThrongDocument into T on demand.

T findOne(Class<T>, Query)

Convenience over find that sets limit(1) and returns the first decoded entity, or null if the result set is empty.

InsertOneResult insert(T, InsertOneOptions)

Encodes the entity into a ThrongDocument (firing @PrePersist before and @PostPersist after encoding) and calls insertOne.

UpdateResult update(Class<T>, Filter, Updates, UpdateOptions)

Calls updateMany and wraps the driver’s UpdateResult so that getModifiedPlusInsertedCount is available (modified count plus 1 if an upsertedId is set).

DeleteResult delete(Class<T>, Filter, DeleteOptions)

Calls deleteMany with the supplied filter.

ThrongIterable<T> aggregate(Class<T>, Pipeline)

Runs the pipeline against the entity’s collection and decodes each output document back into the same entity type. Use when the pipeline preserves the source schema.

ThrongIterable<R> aggregate(Class<S>, Class<R>, Pipeline)

Runs the pipeline against the source entity’s collection and decodes each output document into a separately registered result entity type. Use when the pipeline reshapes documents (for example $group rollups).

Note

insert derives the entity class from the runtime type of the value (value.getClass()), not the declared generic parameter. A value whose runtime class is not registered produces ThrongRuntimeException("Unmapped entity type(…​)").

Three flags:

Flag Meaning

storeNulls

When true, null property values are persisted as BSON null. When false (the typical choice), null-valued properties are omitted from the encoded document. The flag propagates into ThrongPropertiesCodec, ThrongEmbeddedCodec, and ArrayCodec; the encode path skips null writes when the flag is off and writes BSON null otherwise.

createIndexes

When true, indexes declared by the entity’s @Indexed / @Index / @Indexes / @AllIndexes annotations are created at ThrongClient construction via IndexUtility.createIndex on the corresponding collection.

includeCollation

When true, collation settings from each @IndexOptions.collation are applied during index creation. When false, collation is skipped — useful for clusters that do not support the default ICU collator or deployments that store collation rules server-side.

ThrongOptions has a (boolean, boolean, boolean) constructor and fluent setters (setStoreNulls, setCreateIndexes, setIncludeCollation) that return this. Its no-arg constructor is private; use the three-argument form.

@Entity(value)

Class-level. Marks a top-level document.

  • value() — the collection name (required).

  • polymorphic() — must be left at the default @Polymorphic(). An entity with a non-empty @Polymorphic fails mapping (see Limitations).

@Embedded

Class-level. Marks a non-collection document type.

  • polymorphic() — optional. A non-empty value() list triggers polymorphic encode/decode through ThrongPolymorphicEmbeddedCodec.

@Id(value = "_id")

Field-level. Identifies the primary key field.

  • value() — the BSON name. Default _id. Exactly one @Id field per @Entity; missing or duplicate throws ThrongMappingException.

@Property(value = "")

Field-level. Declares a stored field.

  • value() — the BSON name. Empty (the default) means "use the Java field name."

@Codec(value)

Field-level. Binds a specific org.bson.codecs.Codec<?> to the field, overriding the registry.

  • value() — the codec class. The codec is instantiated reflectively via CodecUtility; a type mismatch between the codec’s encoder class and the field type throws ThrongMappingException at registration.

@Polymorphic(value = {}, key = "")

Class-level. Declares a polymorphic hierarchy on an @Embedded class.

  • value() — the permissible concrete subtypes. Empty disables polymorphism.

  • key() — the discriminator field name in BSON. Empty means "use `java/object`" (the legacy default).

All four lifecycle annotations are @Entity-only; declaring any of them on an @Embedded class fails mapping with ThrongLifecycleRejection.reject.

@PreLoad

Must be static. Takes a single BsonDocument parameter. Fires before the entity is decoded. Use it to inspect or transform the raw BSON.

@PostLoad

Instance method, no arguments. Fires after the entity has been decoded. Use it to compute derived state or validate the loaded object.

@PrePersist

Instance method, no arguments. Fires before the entity is encoded. Use it to stamp updatedAt fields or validate state pre-write.

@PostPersist

Instance method. Takes a single BsonDocument parameter. Fires after the encoded BsonDocument has been produced but before it is handed to the driver. Rarely needed; most projects use @PrePersist.

@Indexed(IndexType value = ASCENDING, IndexOptions options = …​)

Field-level. Declares a single-field index.

@Index(String value, IndexType type = ASCENDING)

Component of a compound-index declaration. Not a standalone field annotation.

@Indexes(Index[] value, IndexOptions options = …​)

Class-level (repeatable via @AllIndexes). Declares a compound index comprising the listed @Index elements and shared options.

@AllIndexes(Indexes[] value)

Class-level. Container annotation aggregating multiple @Indexes. Required because @Indexes is itself an array wrapper and not directly @Repeatable-compatible with Java’s annotation inheritance semantics.

@IndexOptions

Carries the MongoDB driver’s full IndexOptions surface: background, unique, name, sparse, expireAfterSeconds, version, weights, defaultLanguage, languageOverride, textVersion, sphereVersion, bits, min, max, storageEngine, partialFilterExpression, collation, wildcardProjection, hidden. Every member has a default; only override the ones that deviate from MongoDB’s standard behavior.

@Collation

Embedded inside @IndexOptions.collation(). Carries the locale and strength settings that the driver’s Collation.builder() understands.

IndexType

Six-case enum: ASCENDING, DESCENDING, HASHED, TEXT, GEO2D, GEO2DSPHERE. Each case knows how to produce a Bson index spec by delegating to com.mongodb.client.model.Indexes.

An entity with single-field indexes, a compound index, and a lifecycle callback:

import org.bson.BsonDocument;
import org.bson.types.ObjectId;
import org.smallmind.mongodb.throng.index.IndexType;
import org.smallmind.mongodb.throng.index.annotation.Index;
import org.smallmind.mongodb.throng.index.annotation.IndexOptions;
import org.smallmind.mongodb.throng.index.annotation.Indexed;
import org.smallmind.mongodb.throng.index.annotation.Indexes;
import org.smallmind.mongodb.throng.lifecycle.annotation.PrePersist;
import org.smallmind.mongodb.throng.mapping.annotation.Entity;
import org.smallmind.mongodb.throng.mapping.annotation.Id;
import org.smallmind.mongodb.throng.mapping.annotation.Property;

@Entity("orders")
@Indexes(                                               (1)
    value   = {@Index(value = "status"),
               @Index(value = "placed_at", type = IndexType.DESCENDING)},
    options = @IndexOptions(name = "status_placedAt_idx"))
public class Order {

  @Id
  private ObjectId id;

  @Indexed                                              (2)
  @Property("customer_id")
  private String customerId;

  @Indexed(value = IndexType.DESCENDING,
           options = @IndexOptions(background = true)) (3)
  @Property("placed_at")
  private long placedAt;

  @Property
  private String status;

  @Property
  private long updatedAt;

  @PrePersist
  private void touch () {
    updatedAt = System.currentTimeMillis();             (4)
  }
}
  1. Compound index on status (ascending) + placed_at (descending), with an explicit name so migrations can reference it.

  2. Single-field ascending index on customer_id with default options.

  3. Single-field descending index on placed_at built in the background so index creation does not block.

  4. Lifecycle callback. Throng fires this before encoding the document on every insert and before every update that uses the encoded-entity path — the typed Updates DSL does not dispatch lifecycle callbacks.

A Filter is built in three steps: pick a field, apply a comparison, and (optionally) negate.

Filter f = Filter.where("status").eq("OPEN");                 (1)
Filter g = Filter.where("price").gte(100).not();              (2)
Filter h = Filter.where("tags").in("urgent", "expedited");    (3)
Filter i = Filter.and(                                        (4)
    Filter.where("status").eq("OPEN"),
    Filter.where("placed_at").gt(since));
Filter j = Filter.empty();                                    (5)
  1. Single comparison.

  2. not() negates the current filter; only legal after a comparison. not() on an uninitialized filter throws IllegalFilterStateException.

  3. in(Object…​) and in(Iterable<?>) both exist. The iterable form is preferred when the values come from a collection.

  4. and and or accept varargs; passing zero filters returns Filter.empty(). Passing a filter that has not had a comparison applied throws IllegalFilterStateException.

  5. "Match everything." Used as a filter on count, find, update, or delete when the caller wants to operate on the whole collection.

Supported comparisons:

Method MongoDB operator

eq(Object)

$eq

ne(Object)

$ne

gt(Object)

$gt

gte(Object)

$gte

lt(Object)

$lt

lte(Object)

$lte

exists(boolean)

$exists

in(Iterable<?>) / in(Object…​)

$in

nin(Object…​)

$nin

regex(Pattern)

$regex

not()

$not (wraps the current filter)

A Query composes a Filter with paging and cursor controls.

Query q = Query.with()
    .filter(Filter.where("status").eq("OPEN"))
    .sort(Sort.on().desc("placed_at").asc("customer_id"))
    .projection(Projections.with()
                          .include("customer_id", "status", "placed_at")
                          .exclude("_id"))
    .skip(100)
    .limit(25)
    .batchSize(50);

Defaults: skip=0, limit=0 (no limit), batchSize=0 (driver default, usually 101 for the first batch). skip accepts a long but the driver only honors an int-sized value.

Sort s = Sort.on()
    .desc("placed_at")
    .asc("customer_id");

Order of invocation is the order applied by the driver.

Projections p = Projections.with()
    .include("customer_id", "status")
    .exclude("_id");

Include and exclude follow MongoDB’s rules: mixing them is legal only when excluding _id.

Updates u = Updates.of()
    .set("status", "FULFILLED")
    .inc("version", 1)
    .setOnInsert("createdAt", now)
    .push("history", event);

Supported operators: set, unset, setOnInsert, inc, mul, max, min, push, addToSet, pull, popFirst, popLast, rename. Each call appends to an ordered list; toBsonDocument combines the list via com.mongodb.client.model.Updates.combine(…​).

A Pipeline is an ordered list of aggregation stages, built with the same fluent style as Filter, Sort, Updates, and Projections. Stage builders accept the existing DSL types directly so a pipeline can reuse a filter or sort already prepared elsewhere.

Pipeline pipeline = Pipeline.begin()
    .match(Filter.where("status").eq("OPEN"))                              (1)
    .sort(Sort.on().desc("placedAt"))                                      (2)
    .project(Projections.with().include("customer_id", "status", "total")) (3)
    .skip(20)
    .limit(10);

List<Order> page = throng.aggregate(Order.class, pipeline).asList();       (4)
  1. $match — reuses the standard Filter DSL.

  2. $sort — reuses the standard Sort DSL.

  3. $project — reuses the standard Projections DSL.

  4. The pipeline output preserves the Order shape, so the single-class aggregate decodes each result back into an Order instance.

Supported stages:

Method MongoDB stage

match(Filter)

$match

sort(Sort)

$sort

project(Projections)

$project

limit(int)

$limit

skip(long)

$skip

count(String)

$count into the named field

unwind(String)

$unwind of the supplied field path (use the $ prefix)

lookup(String, String, String, String)

$lookup left outer join

group(Object, BsonField…​)

$group with accumulators from com.mongodb.client.model.Accumulators

stage(Bson)

escape hatch — appends the supplied stage document verbatim

For pipelines that reshape documents (most commonly $group), pair the source entity with a separate result entity whose mapping matches the output:

@Entity("category_rollups")
public class CategoryRollup {
  @Id  private String id;     // receives the group key
  @Property private Integer total;
  @Property private Integer count;
  /* getters/setters/no-arg */
}

ThrongClient throng = new ThrongClient(
    mongoClient, "orders-db",
    new ThrongOptions(false, true, true),
    Order.class, CategoryRollup.class);                                    (1)

List<CategoryRollup> rollups = throng.aggregate(
    Order.class, CategoryRollup.class,                                     (2)
    Pipeline.begin()
            .group("$category",
                   Accumulators.sum("total", "$amount"),
                   Accumulators.sum("count", 1))
            .sort(Sort.on().desc("total"))).asList();
  1. Both entity classes must be registered with the client up front so each has a codec.

  2. The first class identifies the source collection; the second identifies the decode shape applied to each pipeline output document.

The result entity’s @Id field receives the value of _id from each output document — including null when the pipeline uses group(null, …) to roll up the entire collection into a single bucket.

ThrongIterable<T> exposes two ways to consume a result set:

// Eager
List<Order> open = throng.find(Order.class, q).asList();

// Lazy
try (var cursor = throng.find(Order.class, q).iterator()) {   (1)
  while (cursor.hasNext()) {
    process(cursor.next());
  }
}
  1. The underlying MongoCursor is closeable; rely on try-with-resources or explicit close when draining a long cursor.

Each next() call performs exactly one decode and fires @PreLoad / @PostLoad once. A query with 10,000 matches and Iterator#hasNext/next iteration decodes 10,000 times; asList() is equivalent but eager.

ThrongClient builds a stacked CodecRegistry exactly once during construction:

  1. Driver base + array support. The first layer merges the database’s own registry with an ArrayCodecProvider that wraps every Java array type seen during mapping. The storeNulls setting flows into the array codec so that null elements in a stored array follow the same encoding rule as null scalar properties.

  2. Embedded codecs. The second layer adds one ThrongEmbeddedCodec (or ThrongPolymorphicEmbeddedCodec) per registered @Embedded class. Polymorphic variants dispatch at encode time by inspecting the runtime class and at decode time by reading the discriminator field (default java/object, or whatever @Polymorphic.key() is).

  3. Document pass-through. The outermost layer adds a ThrongDocumentCodec so that a ThrongDocument round-trips without further rewriting.

All filters, updates, and values pass through the outermost registry. That is how a Filter.where("placed_at").gt(Instant.now()) is encoded using the same rules that would encode a stored property.

TranslationUtility.fromBson invokes callbacks in this order during decode:

  1. @PreLoad static method (if present), with the raw BsonDocument.

  2. The codec decodes the document into a new instance.

  3. @PostLoad instance method (if present).

TranslationUtility.toBson invokes callbacks during encode:

  1. @PrePersist instance method (if present).

  2. The codec encodes the instance into a BsonDocument.

  3. @PostPersist instance method (if present), with the encoded BsonDocument.

Callbacks that throw propagate through the triggering operation unchanged; a throwing @PrePersist short-circuits the insert before anything touches the driver.

With storeNulls=false (the typical setting):

  • null property values are omitted from the encoded document;

  • decoding tolerates either a missing field or a BSON null — in both cases the Java field is left at its default (null for references, 0 for primitives);

  • null elements inside a stored array are dropped on encode.

With storeNulls=true:

  • null property values become BSON null;

  • absent fields still decode to the Java default.

The flag affects encode only; decode is symmetrical.

IndexUtility.createIndex collects the entity’s compound indexes (from @Indexes/@AllIndexes) and single-field indexes (from @Indexed), resolves each IndexType into its driver Indexes.ascending / descending / hashed / text / geo2d / geo2dsphere factory call, applies each @IndexOptions to a driver IndexOptions, and calls MongoCollection#createIndex per entry.

If options.isIncludeCollation() is false, the @Collation on each @IndexOptions.collation() is ignored.

Index creation is not transactional and is not idempotent across schema changes. Renaming a field without dropping the old index leaves orphan indexes in place; removing an @Indexed annotation does not drop the server-side index.

  • ThrongClient is safe to share across threads. Its internal state (database handle, codec registry, codec map) is set once during construction and only read thereafter.

  • Filter, Query, Sort, Projections, and Updates are single-use builders; do not mutate one from multiple threads. Each CRUD call is idiomatic: build the query, pass it in, discard.

  • ThrongIterable and its ThrongIterator wrap the driver’s own FindIterable / MongoCursor; the cursor is not thread-safe and must be iterated from one thread.

The exceptions callers will see fall into four groups.

Mapping

ThrongMappingException (checked) is raised during ThrongClient construction when an annotation is wrong, a codec cannot be resolved, an embedded class declares a lifecycle callback, or an entity has zero or multiple @Id fields. It extends org.smallmind.nutsnbolts.lang.FormattedException, so callers declare or catch it.

Reflection

NoSuchMethodException, InstantiationException, IllegalAccessException, and InvocationTargetException propagate from ThrongClient construction when an @Entity, @Embedded, or @Codec class lacks a no-arg constructor or access cannot be granted.

Runtime

ThrongRuntimeException is raised for unmapped entity lookups (Unmapped entity type(…​)), codec dispatch failures in polymorphic encode, and reflection errors inside lifecycle execution. Extends org.smallmind.nutsnbolts.lang.FormattedRuntimeException.

Filter

IllegalFilterStateException (runtime) is thrown when a comparison is applied to a closed filter or when not() is applied to an uninitialized one. UnsupportedOperationException is thrown by Filter.toBsonDocument when the filter has never had a comparison applied — callers compose queries such that every leaf filter has exactly one comparison.

Driver

MongoException and its subclasses pass through unchanged from the underlying driver. DuplicateKeyUtility.idDuplicateKeyException is a small helper for detecting error code 11000 (E11000 duplicate key error) in a MongoWriteException.

ThrongMappingException: Missing id property

The entity has no @Id field. Add one or, if the entity is intended to be embedded rather than top-level, change the annotation from @Entity to @Embedded.

ThrongMappingException: More than one id property

The entity has multiple @Id fields. Keep exactly one.

ThrongMappingException: Lifecycle methods are not supported on embedded types

An @Embedded class declares @PrePersist, @PostPersist, @PreLoad, or @PostLoad. Move the behavior to the parent @Entity — a callback on the parent sees the whole document, including the embedded subtree.

ThrongMappingException: Polymorphism is not supported on entities

An @Entity declares @Polymorphic(value = {…​}). Entities must not use @Polymorphic. If the hierarchy is a top-level collection, store the discriminator as an ordinary field and dispatch application-side; if the hierarchy is embedded, move it into an @Embedded class that can declare @Polymorphic.

ThrongRuntimeException: Unmapped entity type(…​)

A CRUD call referenced a Class that was not passed in the entityClasses vararg to the ThrongClient constructor. Add it.

IllegalAccessException: module … does not open … to module org.smallmind.mongodb.throng

The application runs on a module path and has not opened the package holding its mapped classes. Open it to org.smallmind.mongodb.throng; see Module Path.

IllegalFilterStateException: The filter(…​) is closed

A second comparison was applied to a filter that already had one. Filter.where("x").eq(1).eq(2) is not legal. Split into two filters and combine with Filter.and(…​).

IllegalFilterStateException: The filter(…​) is incomplete

A comparison-less filter was passed to Filter.and, Filter.or, or not(). Apply a comparison method before composing.

UnsupportedOperationException from Filter.toBsonDocument

Same root cause as the incomplete-filter case, surfaced when the filter is handed to count/find/update/delete without a comparison. Add a comparison or use Filter.empty() to match all documents.

ThrongRuntimeException wrapping an ExecutionException during decode

A lifecycle method threw. The underlying exception is the cause; fix the callback and retry.

NumberFormatException during Spring context startup

MongoServerFactoryBean’s pattern has a ` placed after the : port separator. Move the left of the :.

ConfigException: No bootstrap hosts at MongoClient construction

MongoClientSettingsFactoryBean.serverAddresses is null or empty. Confirm MongoServerFactoryBean.serverPattern is set and the spread expression evaluates to at least one value.

MongoWriteException with code 11000

Duplicate key — a unique index refused the write. Use DuplicateKeyUtility.idDuplicateKeyException(mongoWriteException) to classify.

No polymorphism for @Entity

@Polymorphic is an @Embedded-only feature. Top-level hierarchies must encode their discriminator as an ordinary property and dispatch application-side.

No lifecycle callbacks for @Embedded

Lifecycle behavior must live on the parent @Entity. The rejection is enforced by ThrongLifecycleRejection.reject during codec generation.

Partial support for generic containers

List, Map, and similar containers whose element type is @Embedded compile and run but do not participate in automated index processing — indexes declared on the embedded element type are not collected by the parent entity. Containers whose element type uses @Codec will throw a type-mismatch exception at mapping time. The documented workaround is a typed subclass of the container with a parameterized codec, and — for @Embedded element types — to declare the required indexes on the parent entity using @Indexes / @AllIndexes with dotted field paths.

skip is effectively int

Query.skip accepts a long but the underlying driver only honors an int. There is a TODO in Query.java recording the gap; do not pass values beyond Integer.MAX_VALUE.

No aggregate / watch surface

Pipelines, change streams, and bulk writes are not exposed through ThrongClient. Use the driver’s MongoClient directly for those operations.

SCRAM-SHA-1 only in the credential factory

MongoCredentialFactoryBean hard-codes SCRAM-SHA-1. For SCRAM-SHA-256, X.509, Kerberos, AWS IAM, or OIDC, construct the MongoCredential directly and inject it into MongoClientSettingsFactoryBean.

UUID representation is pinned

MongoClientSettingsFactoryBean hard-codes UuidRepresentation.STANDARD. There is no property to override it. Applications reading legacy data encoded with a different representation need to construct MongoClientSettings directly.

No connection-string parser

The settings factory does not accept a mongodb:// / mongodb+srv:// URI. Its inputs are typed components.

Compile-time dependency on Spring

mongodb-utility’s factory classes require `spring-beans. The dependency is optional in the POM, but the classes do not compile without it.

Setting Default Where set

MongoServer.port

27017

MongoServer field initializer.

MongoServerFactoryBean port when no :port is supplied

27017

MongoServerFactoryBean.afterPropertiesSet.

MongoServerFactoryBean.isSingleton

true

MongoServerFactoryBean.

MongoCredentialFactoryBean.isSingleton

true

MongoCredentialFactoryBean.

MongoWriteConcern.isSingleton

false

MongoWriteConcern.

MongoWriteConcern.journaled

false

MongoWriteConcern field initializer.

MongoClientSettingsFactoryBean.isSingleton

true

MongoClientSettingsFactoryBean.

MongoClientSettingsFactoryBean.uuidRepresentation

STANDARD

Hard-coded.

MongoClientFactoryBean lifecycle

create in afterPropertiesSet, close in destroy

MongoClientFactoryBean.

@Id.value

_id

@Id default.

@Property.value

Java field name (empty triggers fallback)

@Property default.

@Indexed.value

ASCENDING

@Indexed default.

@Index.type

ASCENDING

@Index default.

@IndexOptions.background

false

@IndexOptions default.

@IndexOptions.unique

false

@IndexOptions default.

@IndexOptions.expireAfterSeconds

0 (disabled)

@IndexOptions default.

@Collation.locale

simple

@Collation default.

@Collation.strength

TERTIARY

@Collation default.

@Polymorphic.key

"" → java/object

@Polymorphic default.

Query.skip

0

Query field initializer.

Query.limit

0 (no limit)

Query field initializer.

Query.batchSize

0 (driver default)

Query field initializer.

Before shipping an integration:

  1. Confirm the MongoServerFactoryBean produces a non-empty ServerAddress[] — log the array at startup if needed.

  2. Pick a MongoAcknowledgment consistent with the write durability your service requires, and set journaled only when the chosen level is journable.

  3. Pass every @Entity and @Embedded class your service uses to the ThrongClient constructor — unregistered classes fail at first access.

  4. Set createIndexes=true for services that own the schema; set it to false for readers that share a collection with an authoritative writer.

  5. For each @Entity, confirm exactly one @Id and no @Polymorphic; for each @Embedded, confirm no lifecycle annotations.

  6. Verify the filter/update DSLs use BSON field names, not Java field names — Throng does not translate.

  7. Close any ThrongIterator you iterate manually; asList() closes internally.

  8. Close the surrounding Spring context on shutdown so the MongoClientFactoryBean.destroy runs and drains the driver’s connection pool.

smallmind-mongodb turns the two rote jobs of using the MongoDB Java driver — standing up a MongoClient and mapping Java classes to documents — into two small, orthogonal modules. mongodb-utility is a set of Spring FactoryBean implementations that produce ServerAddress[], MongoCredential, WriteConcern, MongoClientSettings, and a managed MongoClient. mongodb-throng is an annotation-driven mapper whose ThrongClient vends typed CRUD over @Entity classes, with fluent DSLs for filters, updates, sorts, and projections, all composed over the driver’s own CodecRegistry. Together they cover the path from XML configuration to typed database access without the driver’s builder vocabulary showing up in calling code.