Quarkus Extension: CDI Integration for Morphium

Jakarta Data TCK: 73 of 73

The repositories of this module run on morphium-jakarta-data, which passes all 73 tests of the standalone Jakarta Data 1.0 TCK suite (from 7.0) — see Conformance.

quarkus-morphium is an optional Morphium module that integrates Morphium into Quarkus applications via a CDI producer, type-safe @ConfigMapping configuration, declarative transactions, health checks, Dev Services, Dev UI integration, and GraalVM native-image support. It also pulls in morphium-jakarta-data and generates Jakarta Data @Repository implementations at build time via Gizmo bytecode generation — no runtime reflection, no dynamic proxies.

Optional module — the Morphium core does not depend on it

de.caluga:morphium has zero compile- or runtime dependency on this extension, on Quarkus, or on jakarta.data-api. Building the Morphium reactor without this module (-DskipExtensions) produces an unchanged core. You only need quarkus-morphium if you are building a Quarkus application against MongoDB via Morphium.

What it provides

  • CDI producer — @Inject Morphium morphium; anywhere in a Quarkus bean, backed by a single, application-scoped Morphium instance configured from application.properties; more databases are named instances.
  • Type-safe configuration — every setting lives under quarkus.morphium.* as a @ConfigMapping, validated at build time instead of failing at runtime on a typo.
  • Declarative transactions — @MorphiumTransactional on a CDI bean method wraps the method body in startTransaction()/commitTransaction()/abortTransaction() automatically, with MorphiumTransactionEvent CDI events (BEFORE_COMMIT, AFTER_COMMIT, AFTER_ROLLBACK) for cross-cutting reactions (audit logging, outbox publishing, etc.). Gracefully degrades to non-transactional execution on Azure CosmosDB, which is auto-detected.
  • Jakarta Data repositories — declare a @Repository interface extending CrudRepository/MorphiumRepository from morphium-jakarta-data; the extension's build-time processor generates the implementation via Gizmo, with no reflection at runtime. See Jakarta Data for the full query-derivation, JDQL, and pagination feature set — everything documented there works identically once generated by this extension.
  • Health checks — MicroProfile liveness (/q/health/live), readiness (/q/health/ready, with connection-pool metadata), and startup (/q/health/started) probes registered automatically via SmallRye Health.
  • Micrometer metrics — connection pool, cache and write-buffer gauges and counters (morphium.driver.*, morphium.cache.*, morphium.write_buffer.*) and a timer for the update operations (morphium.operations.duration). Active when Micrometer is on the application's classpath; see Metrics.
  • Dev Services — a MongoDB container (optionally as a single-node replica set, so transactions and change streams work out of the box) starts automatically in dev and test mode when no explicit quarkus.morphium.hosts is configured — no Docker Compose, no manual setup.
  • Dev UI card — live MongoDB connection info (hosts, database, replica-set mode, container ID) at /q/dev-ui/.
  • GraalVM native-image support — every @Entity/@Embedded class (and Morphium's own reflection-dependent internals) is registered for reflection at build time; no manual reflect-config.json.
  • MorphiumId JSON serialization — entities with @Id MorphiumId id serialize to a plain 24-character hex string over REST (both Jackson and JSON-B), and parse back from one — no serializer to write by hand.
  • Migration runner — a lightweight, MongoDB-backed schema/data migration mechanism (quarkus.morphium.migration.*) with a distributed lock, so multiple application instances don't race to apply the same migration.

Installation

<dependency>
  <groupId>de.caluga</groupId>
  <artifactId>quarkus-morphium</artifactId>
  <version>6.3.9</version>
</dependency>

This module follows Morphium's regular release versioning and is released in lockstep with Morphium core; there is no separate version line to track. Building the reactor (mvn -pl quarkus-morphium -am verify) builds this extension against the exact Morphium core version in the same build.

The SCRAM library: scram-client 3.3 or newer

Morphium authenticates with SCRAM through com.ongres.scram:scram-client and manages version 3.4 (it fixes CVE-2025-59432, a timing attack, in 3.2, and CVE-2026-53712, a downgrade of channel binding, in 3.3). The BOM of the application wins over the version of a library: the Quarkus 3.40.1 platform BOM manages 3.3, which has both fixes, and the 3.32.3 BOM manages 3.2, which lacks the second one (the versions in between were not checked). With an older or unchecked Quarkus version pin the version in the dependencyManagement of the application (it wins over the imported Quarkus BOM):

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.ongres.scram</groupId>
      <artifactId>scram-client</artifactId>
      <version>3.4</version>
    </dependency>
  </dependencies>
</dependencyManagement>

Morphium itself is not affected by CVE-2026-53712, because it authenticates with ChannelBindingPolicy.DISABLE, but a dependency scanner reports the old version. The tests of this repository and the Quarkus Morphium Showcase run on 3.4.

Configuration Reference

All properties live under quarkus.morphium.*. This is not the complete list — see the Antora documentation in the module directory (quarkus-morphium/docs/) for every property — but covers the most commonly used ones, each verified directly against the @ConfigMapping source.

PropertyDefaultDescriptionSource
quarkus.morphium.hostslocalhost:27017Comma-separated host:port listMorphiumConnectionConfig.java:35
quarkus.morphium.database(required)MongoDB database nameMorphiumConnectionConfig.java:38
quarkus.morphium.username / .password--Optional credentialsMorphiumConnectionConfig.java:41,44
quarkus.morphium.auth-databaseadminAuthentication databaseMorphiumConnectionConfig.java:48
quarkus.morphium.read-preferenceprimaryRead preferenceMorphiumConnectionConfig.java:56
quarkus.morphium.index-checkcreate-on-startupIndex management strategy (create-on-startup, warn-on-startup, create-on-write-new-col, no-check)MorphiumConnectionConfig.java:75
quarkus.morphium.max-connections250Connection pool sizeMorphiumConnectionConfig.java:91
quarkus.morphium.max-wait-time2000Max wait time (ms) for a pooled connectionMorphiumConnectionConfig.java:101
quarkus.morphium.default-query-timeout-ms0 (disabled)Server-side maxTimeMS applied to queries without an explicit per-query timeoutMorphiumConnectionConfig.java:116
quarkus.morphium.atlas-url--MongoDB Atlas SRV connection string (overrides hosts)MorphiumConnectionConfig.java:122
quarkus.morphium.driver-namePooledDriverPooledDriver (production) or InMemDriver (tests, no MongoDB needed)MorphiumConnectionConfig.java:129
quarkus.morphium.replica-set-name--MongoDB replica set name (required for transactions)MorphiumConnectionConfig.java:136
quarkus.morphium.connect-retries5Connection attempts before giving upMorphiumConnectionConfig.java:145
quarkus.morphium.cache.read-cache-enabledtrueEnable query result cacheCacheConfig.java:31
quarkus.morphium.cache.global-valid-time60000Cache TTL in millisecondsCacheConfig.java:27
quarkus.morphium.use-bson-date-for-java-time--Store Instant, LocalDate, LocalTime and LocalDateTime as BSON ISODate. Unset leaves the previous per-type behaviour untouched. Mapper path only: maps you build yourself (raw driver commands, the update map of findOneAndUpdate) need java.util.Date, see configuration referenceMorphiumConnectionConfig.java
quarkus.morphium.enum-typeSTRINGHow an enum is stored in a field without @Enumerated: STRING (name) or ORDINAL (position, sorts in the order of the constants). See EnumsMorphiumConnectionConfig.java
quarkus.morphium.local-date-time.use-bson-datetrueDeprecated (removal: 7.0), use use-bson-date-for-java-time; reaches LocalDateTime onlyLocalDateTimeConfig.java
quarkus.morphium.ssl.enabledfalseEnable TLSSslConfig.java:48
quarkus.morphium.ssl.auth-mechanism--MONGODB-X509 for client-certificate authSslConfig.java:59
quarkus.morphium.ssl.keystore-path / .keystore-password--Keystore for client-cert auth / mutual TLSSslConfig.java:65,68
quarkus.morphium.ssl.truststore-path / .truststore-password--Truststore for server certificate validationSslConfig.java:74,77
quarkus.morphium.ssl.invalid-hostname-allowedfalseAllow invalid hostnames (dev only)SslConfig.java:84
quarkus.morphium.ssl.tls-configuration-name--Use a named Quarkus TLS registry configuration instead of explicit keystore/truststore pathsSslConfig.java:108
quarkus.morphium.devservices.enabledtrueEnable automatic MongoDB container in dev/test modeMorphiumDevServicesBuildTimeConfig.java:45
quarkus.morphium.devservices.image-namemongo:8Docker image for Dev ServicesMorphiumDevServicesBuildTimeConfig.java:52
quarkus.morphium.devservices.database-namemorphium-devDatabase name injected by Dev ServicesMorphiumDevServicesBuildTimeConfig.java:59
quarkus.morphium.devservices.replica-settrueStart MongoDB as a single-node replica set (enables transactions)MorphiumDevServicesBuildTimeConfig.java:72
quarkus.morphium.messaging.queue-name / .window-size / .poll-pause / .multithreaded / .use-change-stream / .sender-id / .auto-answerMorphium's defaultsSettings of the injected MorphiumMessaging, see MessagingMorphiumMessagingConfig.java
quarkus.morphium.health.enabledtrueEnable liveness/readiness/startup health checksMorphiumHealthBuildTimeConfig.java:41
quarkus.morphium.observability.enabledtrueRegister the Micrometer meters (only effective when Micrometer is on the classpath)MorphiumObservabilityConfig.java
quarkus.morphium.observability.include-storage-listener-metricstrueTime the update operations (morphium.operations.duration); adds a storage listener to the Morphium instanceMorphiumObservabilityConfig.java
quarkus.morphium.migration.migrate-at-startfalseRun pending migrations automatically on startupMorphiumMigrationConfig.java:40
quarkus.morphium.migration.change-log-collectionmorphiumChangeLogCollection tracking executed migrationsMorphiumMigrationConfig.java:44
quarkus.morphium.migration.lock-collectionmorphiumMigrationLockCollection used for the distributed migration lockMorphiumMigrationConfig.java:48
quarkus.morphium.migration.lock-ttl-seconds60Migration-lock TTL in secondsMorphiumMigrationConfig.java:56

Named instances

A second (third, ...) database needs no second application: configure it under quarkus.morphium.named."name".* and inject it with the @MorphiumInstance("name") qualifier (MOR-032).

quarkus.morphium.database=orders
quarkus.morphium.hosts=mongo-a:27017

quarkus.morphium.named."analytics".database=analytics
quarkus.morphium.named."analytics".hosts=mongo-b:27017,mongo-c:27017
quarkus.morphium.named."analytics".username=reader
quarkus.morphium.named."analytics".password=...
@Inject Morphium orders;                                   // the default instance, as before
@Inject @MorphiumInstance("analytics") Morphium analytics; // quarkus.morphium.named."analytics".*

A named instance takes the same settings as the default one (hosts, database, credentials, driver-name, max-connections, cache.*, ssl.*, index-check, ...), each with the same default. The names are read from the configuration keys at build time, because a qualifier needs a bean per name; the values can still change at run time, but a name cannot be added then. An instance is created on first use and closed on shutdown. The entities of the application are known to every instance (with index-check=create-on-startup the indexes of all entities are created in each database; set no-check for an instance that holds few of them). What belongs to the default instance only: migrations, Dev Services, Micrometer metrics, the Dev UI card and @MorphiumTransactional. The readiness check "Morphium named instances readiness check" covers every named instance.

Messaging

Morphium's MongoDB-backed message queue is a CDI bean as well (MOR-033): inject MorphiumMessaging, or let a bean listen to a topic.

@Inject MorphiumMessaging messaging;                      // on the default Morphium instance, created on first use

messaging.sendMessage(new Msg("orders", "created", "4711"));

@ApplicationScoped
@MorphiumMessageListener(topic = "orders")                // topic = {"a", "b"} for several
public class OrderListener implements MessageListener<Msg> {
    @Override
    public Msg onMessage(MorphiumMessaging messaging, Msg m) {
        ...;
        return null;                                      // or an answer
    }
}

The messaging is created from the default Morphium instance, started, given the beans that carry @MorphiumMessageListener (they keep their scope and are not removed as unused) and terminated when the application stops. A bean with the annotation makes the extension create the messaging at startup, so its messages are processed without anybody injecting the messaging. Settings, all optional and left to Morphium's own defaults when not set: quarkus.morphium.messaging.queue-name, .window-size, .poll-pause (ms), .multithreaded, .use-change-stream, .sender-id, .auto-answer. A message that the sender sends to itself is not delivered to its own listeners; use sendMessageToSelf for that. Messaging of named instances is not wired; create it from the injected instance with analytics.createMessaging().

Metrics

With Micrometer on the classpath (for example quarkus-micrometer-registry-prometheus) the extension registers these meters, all tagged with database:

MeterTypeMeaning
morphium.driver.connections.pool, .in_usegaugeconnections in the pool / borrowed
morphium.driver.connections.borrowed, .releasedcountercumulative
morphium.driver.threads.waitinggaugethreads waiting for a connection
morphium.driver.errors, .failoverscountercumulative
morphium.cache.hit_ratio, .entries, morphium.write_buffer.entriesgaugecache and write buffer
morphium.operations.durationtimerupdate operations; tags operation=update, update_type (set, inc, push, ...) and entity

The timer covers every update that fires the storage-listener events: the writer path (Query.set, inc, push, pull, ..., the bulk context), the update builder (Query.modify()) and findOneAndUpdate(Map), updateOne and updateMany. The update_type is the operator of the call (set, inc, push, ...), custom for an update with several operators. A write that fails is not timed, because no event follows it. A write that a buffered writer flushes on another thread is not timed either.

Quick Example

@Entity(collectionName = "products")
public class Product {
    @Id private MorphiumId id;
    private String name;
    private double price;
    private String category;
    @Version private long version;
    // getters/setters omitted
}

@Repository
public interface ProductRepository extends MorphiumRepository<Product, MorphiumId> {
    List<Product> findByCategory(String category);

    @OrderBy("price")
    List<Product> findByPriceGreaterThan(double minPrice);
}

@ApplicationScoped
public class ProductService {
    @Inject ProductRepository products;

    @MorphiumTransactional
    public Product create(String name, double price, String category) {
        var p = new Product();
        p.setName(name);
        p.setPrice(price);
        p.setCategory(category);
        return products.insert(p);
    }
}
quarkus.morphium.database=my-app-db
# Dev Services starts MongoDB automatically — no further config needed in dev/test.

Testing without Docker

%test.quarkus.morphium.driver-name=InMemDriver
%test.quarkus.morphium.database=test-db

InMemDriver is Morphium's in-memory MongoDB emulation — @QuarkusTest classes run against it with no container and no external MongoDB, exactly like the core Morphium test suite.

Testing against a real MongoDB

The module quarkus-morphium-testing (test scope) has the helpers for application tests:

@QuarkusTest
@TestProfile(MongoMorphiumTestProfile.class)      // a real MongoDB, see below
@ExtendWith(ResetMorphiumExtension.class)          // an empty database before each test
class OrderServiceTest {
    @Inject Morphium morphium;

    @Test
    void cancelsAnOrder() {
        MorphiumTestSupport.load(morphium, order("o1"), order("o2"));   // fixtures, stored like the application stores
        ...
    }
}
  • MongoMorphiumTestProfile runs the test with the pooled driver against a MongoDB container that Dev Services starts. With MORPHIUM_TEST_HOSTS=host:27017 (environment variable or system property) it uses that server instead. The tests use their own database (morphium-test, override database() in a subclass); a subclass can also ask for a replica set (replicaSet()), which transactions need. InMemMorphiumTestProfile stays the choice for tests without a server.
  • MorphiumTestSupport.reset(morphium) removes the documents of all collections of the database and clears the cache. It deletes instead of dropping, so the collections keep their indexes. ResetMorphiumExtension calls it before each test.
  • MorphiumTestSupport.load(morphium, entities...) stores the entities with Morphium.store.

Full Documentation

This page is an overview. The complete documentation — getting started, entity mapping, configuration reference, transactions, health checks, Dev Services, Jakarta Data repositories, testing, and advanced topics — lives as an Antora documentation module in the repository, at quarkus-morphium/docs/ (source pages under quarkus-morphium/docs/modules/ROOT/pages/):

quarkus-morphium/docs/modules/ROOT/pages/

Antora docs are not part of this site's build

This MkDocs site (the pages under docs/, including this one) and the Antora documentation under quarkus-morphium/docs/ are two separate, coexisting toolchains — the Antora source is not currently built or published by this repository's deploy-docs.yml workflow. Until a publishing decision is made, browse the Antora pages directly on GitHub via the link above, or render them locally with the Antora CLI from quarkus-morphium/docs/antora.yml.

See also Jakarta Data for the framework-agnostic repository runtime that this extension builds on, and PoppyDB for Morphium's other optional module.

← Back to Documentation Hub