Atomic Updates
Update builder, leases, derived updateBy methods, rejected writes
What Morphium Offers
Several workers compete for the same tickets and for one lease. The update must be decided by the database in one command:
a worker that reads "NEW" and then writes "RUNNING" loses against another one in between. Query.modify() builds one atomic update with the field
names translated, the values mapped like store() maps them, @LastChange set, and a typed outcome (UPDATED, NOT_MATCHED,
DUPLICATE_KEY) instead of a null that can mean three things.
The Challenge
With 6.x, a write that the server rejected (a unique index, a path below a scalar) returned as if it had happened, and a hand-built findAndModify map needed
Date.from(...), snake_case keys and a hand-made duplicate key check. In 7.0 a rejected write raises a MorphiumDriverException, and the typed API does the rest.
Morphium Features Used
Claiming a ticket
The condition (state = NEW) and the change are one command; exactly one of two workers wins.
UpdateOutcome<JobTicket> outcome = morphium.createQueryFor(JobTicket.class) .f(JobTicket.Fields.id).eq(ticketId) .f(JobTicket.Fields.state).eq(JobState.NEW) .modify() .set(JobTicket.Fields.state, JobState.RUNNING) // an enum, stored by name .set(JobTicket.Fields.owner, worker) .set(JobTicket.Fields.startedAt, Instant.now()) // an Instant, stored as a date .inc(JobTicket.Fields.attempts, 1) .tryFindOneAndUpdate(ReturnDocument.AFTER); switch (outcome.getKind()) { case UPDATED -> /* this worker won, outcome.getDocument() is the ticket */; case NOT_MATCHED -> /* somebody else was faster, or the ticket does not exist */; }
A lease
LeaseManager<WorkLease> leases = LeaseManager.of(morphium, WorkLease.class, "ownerName", "expiresAt"); LeaseResult<WorkLease> result = leases.tryAcquire("nightly-import", worker, Duration.ofSeconds(60)); if (result.isAcquired()) { /* the lease is held until result.getLease().getExpiresAt() */ } leases.release("nightly-import", worker);
Derived update methods
@Repository public interface JobTicketRepository extends BasicRepository<JobTicket, String> { long updateByState(JobState state, @Param("owner") String owner); // updateMany Optional<JobTicket> updateByIdAndState(String id, JobState state, @Param("owner") String owner); // findAndModify }
A rejected write
try { query.f("id").eq(ticketId).set("code", newCode); // the code has a unique index } catch (MorphiumDriverException e) { if (e.isDuplicateKey()) { /* 6.x ignored the reply of the server and returned as if it had written */ } }
Related Documentation
- API Reference — Atomic update builder, LeaseManager
- Update Pitfalls — raw maps, upserts, rejected writes
- Conditional Writes — leases, claims, run-once markers
- Jakarta Data — @AtomicUpdate, updateBy...
- Migrating from 6 to 7 — what changed for writes