Domain Modeling and Database Implementation

The business model before the endpoints: payment identity, money as minor units, versioned migrations, indexes from queries, preserving source data and persistence boundaries.

  • Advanced
  • About 18 minutes
  • Includes an exercise and a knowledge check

The concept Model the business, not the payload

Do not copy every API field into a database table. The provider’s payload and Apex’s internal model serve different purposes. The internal model reflects Apex’s business concepts (payment transaction, settlement record, reconciliation result, exception case, audit event, provider, ingestion batch) and supports the workflows the platform owns.

Two identifiers Payment identity

textpayment_transaction (logical columns)

id                        internal Apex identifier
provider_id               which provider sent it
provider_transaction_id   the provider’s own identifier
loan_account_id
amount_minor_units
currency
provider_status
transaction_timestamp     when the provider says it happened (UTC)
received_timestamp        when Apex received it (UTC)
processing_status         RECEIVED, NORMALIZED or REJECTED
payload_sha256            fingerprint of the normalized payload
source_payload_reference  where the protected original is kept
created_at, updated_at

UNIQUE (provider_id, provider_transaction_id)

The internal ID identifies the Apex record; the provider transaction ID identifies the transaction in the provider’s world. Never assume an external ID is globally unique unless the provider contract says so. The uniqueness key must match the provider’s identifier scope: per provider here, perhaps per provider and region elsewhere.

Financial precision Money is not a double

On the left, a photo of a handwritten business ledger from 1857 with columns of dollars and cents. On the right, real Java output: with a double, 0.10 plus 0.20 is 0.30000000000000004 and does not equal 0.30. With a Money record in minor units, 10 plus 20 cents is 30 cents, 425.50 USD is 42550 minor units, 4255 yen is 4255 minor units because yen has no decimals, and 425.505 USD is rejected.
A bookkeeper counts every cent exactly. So must the code.

javaMoneyDemo.java: an exact Money type

import java.math.BigDecimal;
import java.util.Currency;

public class MoneyDemo {

    /** An amount in the currency's smallest unit (cents for USD), with the currency always attached. */
    record Money(long amountMinorUnits, Currency currency) {
        Money {
            if (currency == null) throw new IllegalArgumentException("currency is required");
        }

        /** Parses a decimal string such as "425.50" exactly, or rejects it. Never goes through double. */
        static Money parse(String amount, String currencyCode) {
            Currency c = Currency.getInstance(currencyCode);
            BigDecimal value = new BigDecimal(amount);
            if (value.scale() > c.getDefaultFractionDigits()) {
                throw new IllegalArgumentException(amount + " has more decimals than " + currencyCode + " allows");
            }
            long minor = value.movePointRight(c.getDefaultFractionDigits()).longValueExact();
            return new Money(minor, c);
        }

        Money plus(Money other) {
            if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
            return new Money(Math.addExact(amountMinorUnits, other.amountMinorUnits), currency);
        }
    }

    public static void main(String[] args) {
        double a = 0.10, b = 0.20;
        System.out.println("double: 0.10 + 0.20 = " + (a + b));
        System.out.println("double: equals 0.30? " + (a + b == 0.30));

        Money p1 = Money.parse("0.10", "USD");
        Money p2 = Money.parse("0.20", "USD");
        System.out.println("Money:  10 + 20 cents = " + p1.plus(p2).amountMinorUnits() + " cents");

        Money payment = Money.parse("425.50", "USD");
        System.out.println("425.50 USD -> " + payment.amountMinorUnits() + " minor units");
        System.out.println("JPY has " + Currency.getInstance("JPY").getDefaultFractionDigits()
                + " decimals: 4255 JPY -> " + Money.parse("4255", "JPY").amountMinorUnits() + " minor units");
        try {
            Money.parse("425.505", "USD");
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}

Output

double: 0.10 + 0.20 = 0.30000000000000004
double: equals 0.30? false
Money:  10 + 20 cents = 30 cents
425.50 USD -> 42550 minor units
JPY has 0 decimals: 4255 JPY -> 4255 minor units
Rejected: 425.505 has more decimals than USD allows

Real output from Java 17.0.18 running this program (fictional data), November 22, 2026.

Three details matter. The amount is parsed from a decimal string with BigDecimal and never passes through a double. The number of decimals comes from the currency’s metadata, so yen (0 decimals) works as well as dollars (2). Arithmetic uses Math.addExact, which throws instead of silently overflowing. BigDecimal with a controlled scale and rounding mode is an equally valid choice: what matters is that precision is deliberate.

Schema changes Layers and versioned migrations

Left, five layers: the controller handles HTTP, the application service runs the workflow and owns the transaction, the domain logic holds business rules with no HTTP and no SQL, the repository hides storage, and the database is PostgreSQL. Not allowed: SQL in a controller, HTTP classes in the domain. Right, versioned migrations V1 provider, V2 payment transaction, V3 settlement record, V4 reconciliation result, V5 exception case, V6 audit event: version controlled and reviewed, repeatable in a fresh environment, tested on realistic data, compatible with release and rollback. Do not rely on automatic schema generation in production.
Layers with rules, and a schema with a reviewed history.

sqlIndexes come from the queries finance runs

-- Search by loan account and by date range on the transaction screen
CREATE INDEX idx_payment_loan_account ON payment_transaction (loan_account_id);
CREATE INDEX idx_payment_received_at  ON payment_transaction (received_timestamp);

-- The workbench lists results by status
CREATE INDEX idx_reconciliation_status ON reconciliation_result (match_status);

The unique constraint on (provider_id, provider_transaction_id) already creates an index, so lookups by provider transaction ID need no extra one. Validate every index against real query plans and data distribution: each one speeds up reads but slows down writes and uses storage.

Traceability Preserve the original source

OptionFits when
Raw payload in a protected database columnPayloads are small and access is tightly controlled
Raw payload in encrypted object storage, referenced from the rowPayloads are large or retention rules differ from the row’s
A protected subset plus a SHA-256 digest of the originalPrivacy rules forbid keeping the full payload

Practice Implement persistence

Practical exercise

Exercise 03: a working database layer

Build the persistence for payments and settlements.

  1. Core entities and migrations.
  2. Repositories behind persistence interfaces.
  3. The unique transaction constraint and the indexes your queries need.
  4. Repository tests on a real PostgreSQL.
  5. A source-record traceability mechanism.
Show sample test names
  • rejectsSecondRowWithSameProviderAndTransactionId: the unique constraint holds.
  • allowsSameTransactionIdFromDifferentProviders: the uniqueness scope is per provider.
  • storesAmountAsMinorUnitsWithCurrency: 425.50 USD is stored as 42550 and USD.
  • keepsSourcePayloadReference: every payment row points to its protected original.

3 questions

Check your understanding

1. Why avoid Java double for money?
2. Why not trust a provider transaction ID to be globally unique?
3. Where should SQL run?
Answer every question to submit.

What you can do now

  • Design payment identity with a correct uniqueness scope.
  • Represent money exactly with its currency.
  • Use versioned migrations and query-driven indexes.
  • Preserve and protect source data.