Quarkus Extension: CDI Integration for Morphium
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:morphiumhas zero compile- or runtime dependency on this extension, on Quarkus, or onjakarta.data-api. Building the Morphium reactor without this module (-DskipExtensions) produces an unchanged core. You only needquarkus-morphiumif 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-scopedMorphiuminstance configured fromapplication.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 —
@MorphiumTransactionalon a CDI bean method wraps the method body instartTransaction()/commitTransaction()/abortTransaction()automatically, withMorphiumTransactionEventCDI 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
@Repositoryinterface extendingCrudRepository/MorphiumRepositoryfrommorphium-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.hostsis 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/@Embeddedclass (and Morphium's own reflection-dependent internals) is registered for reflection at build time; no manualreflect-config.json. MorphiumIdJSON serialization — entities with@Id MorphiumId idserialize 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.
| Property | Default | Description | Source |
|---|---|---|---|
quarkus.morphium.hosts | localhost:27017 | Comma-separated host:port list | MorphiumConnectionConfig.java:35 |
quarkus.morphium.database | (required) | MongoDB database name | MorphiumConnectionConfig.java:38 |
quarkus.morphium.username / .password | -- | Optional credentials | MorphiumConnectionConfig.java:41,44 |
quarkus.morphium.auth-database | admin | Authentication database | MorphiumConnectionConfig.java:48 |
quarkus.morphium.read-preference | primary | Read preference | MorphiumConnectionConfig.java:56 |
quarkus.morphium.index-check | create-on-startup | Index management strategy (create-on-startup, warn-on-startup, create-on-write-new-col, no-check) | MorphiumConnectionConfig.java:75 |
quarkus.morphium.max-connections | 250 | Connection pool size | MorphiumConnectionConfig.java:91 |
quarkus.morphium.max-wait-time | 2000 | Max wait time (ms) for a pooled connection | MorphiumConnectionConfig.java:101 |
quarkus.morphium.default-query-timeout-ms | 0 (disabled) | Server-side maxTimeMS applied to queries without an explicit per-query timeout | MorphiumConnectionConfig.java:116 |
quarkus.morphium.atlas-url | -- | MongoDB Atlas SRV connection string (overrides hosts) | MorphiumConnectionConfig.java:122 |
quarkus.morphium.driver-name | PooledDriver | PooledDriver (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-retries | 5 | Connection attempts before giving up | MorphiumConnectionConfig.java:145 |
quarkus.morphium.cache.read-cache-enabled | true | Enable query result cache | CacheConfig.java:31 |
quarkus.morphium.cache.global-valid-time | 60000 | Cache TTL in milliseconds | CacheConfig.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 reference | MorphiumConnectionConfig.java |
quarkus.morphium.enum-type | STRING | How an enum is stored in a field without @Enumerated: STRING (name) or ORDINAL (position, sorts in the order of the constants). See Enums | MorphiumConnectionConfig.java |
quarkus.morphium.local-date-time.use-bson-date | true | Deprecated (removal: 7.0), use use-bson-date-for-java-time; reaches LocalDateTime only | LocalDateTimeConfig.java |
quarkus.morphium.ssl.enabled | false | Enable TLS | SslConfig.java:48 |
quarkus.morphium.ssl.auth-mechanism | -- | MONGODB-X509 for client-certificate auth | SslConfig.java:59 |
quarkus.morphium.ssl.keystore-path / .keystore-password | -- | Keystore for client-cert auth / mutual TLS | SslConfig.java:65,68 |
quarkus.morphium.ssl.truststore-path / .truststore-password | -- | Truststore for server certificate validation | SslConfig.java:74,77 |
quarkus.morphium.ssl.invalid-hostname-allowed | false | Allow 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 paths | SslConfig.java:108 |
quarkus.morphium.devservices.enabled | true | Enable automatic MongoDB container in dev/test mode | MorphiumDevServicesBuildTimeConfig.java:45 |
quarkus.morphium.devservices.image-name | mongo:8 | Docker image for Dev Services | MorphiumDevServicesBuildTimeConfig.java:52 |
quarkus.morphium.devservices.database-name | morphium-dev | Database name injected by Dev Services | MorphiumDevServicesBuildTimeConfig.java:59 |
quarkus.morphium.devservices.replica-set | true | Start 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-answer | Morphium's defaults | Settings of the injected MorphiumMessaging, see Messaging | MorphiumMessagingConfig.java |
quarkus.morphium.health.enabled | true | Enable liveness/readiness/startup health checks | MorphiumHealthBuildTimeConfig.java:41 |
quarkus.morphium.observability.enabled | true | Register the Micrometer meters (only effective when Micrometer is on the classpath) | MorphiumObservabilityConfig.java |
quarkus.morphium.observability.include-storage-listener-metrics | true | Time the update operations (morphium.operations.duration); adds a storage listener to the Morphium instance | MorphiumObservabilityConfig.java |
quarkus.morphium.migration.migrate-at-start | false | Run pending migrations automatically on startup | MorphiumMigrationConfig.java:40 |
quarkus.morphium.migration.change-log-collection | morphiumChangeLog | Collection tracking executed migrations | MorphiumMigrationConfig.java:44 |
quarkus.morphium.migration.lock-collection | morphiumMigrationLock | Collection used for the distributed migration lock | MorphiumMigrationConfig.java:48 |
quarkus.morphium.migration.lock-ttl-seconds | 60 | Migration-lock TTL in seconds | MorphiumMigrationConfig.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:
| Meter | Type | Meaning |
|---|---|---|
morphium.driver.connections.pool, .in_use | gauge | connections in the pool / borrowed |
morphium.driver.connections.borrowed, .released | counter | cumulative |
morphium.driver.threads.waiting | gauge | threads waiting for a connection |
morphium.driver.errors, .failovers | counter | cumulative |
morphium.cache.hit_ratio, .entries, morphium.write_buffer.entries | gauge | cache and write buffer |
morphium.operations.duration | timer | update 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
...
}
}
MongoMorphiumTestProfileruns the test with the pooled driver against a MongoDB container that Dev Services starts. WithMORPHIUM_TEST_HOSTS=host:27017(environment variable or system property) it uses that server instead. The tests use their own database (morphium-test, overridedatabase()in a subclass); a subclass can also ask for a replica set (replicaSet()), which transactions need.InMemMorphiumTestProfilestays 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.ResetMorphiumExtensioncalls it before each test.MorphiumTestSupport.load(morphium, entities...)stores the entities withMorphium.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 underquarkus-morphium/docs/are two separate, coexisting toolchains — the Antora source is not currently built or published by this repository'sdeploy-docs.ymlworkflow. 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 fromquarkus-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.