Video in progress

How do you design the Hibernate mapping and database columns for a domain that deals with money amounts and currencies?

BigDecimal in Java (or a long in minor units), numeric(precision, scale) in the database, never double/float. An amount and its currency travel together, so I make an @Embeddable Money(amount, currency). The rounding rule lives in one place, and the scale is set explicitly per currency.

📖 Answer

Everybody knows the problem with double: 0.1 + 0.2 != 0.3. But in financial systems the bugs usually show up in subtler places.

Mapping:

@Embeddable
public record Money(
        @Column(name = "amount", precision = 19, scale = 2, nullable = false) BigDecimal amount,
        @Column(name = "currency", length = 3, nullable = false) String currency) {

    public Money {
        amount = amount.setScale(2, RoundingMode.HALF_EVEN);   // one rule
    }

    public Money plus(Money o) {
        if (!currency.equals(o.currency)) throw new IllegalArgumentException("valyuta har xil");
        return new Money(amount.add(o.amount), currency);
    }
}

If one entity has several amounts, you separate the column names with @AttributeOverride (price_amount, price_currency).

What I pay attention to:

  • BigDecimal.equals() compares the scale too: 1.0 and 1.00 are not equal. When numeric(19,2) comes from the database the scale is 2, while a value created in Java may have a different one, so dirty checking can decide "changed" on every flush and send an UPDATE. Normalizing the scale in the constructor fixes this;
  • currencies have different scales: in practice UZS does not use tiyin, JPY has no fractional part, some currencies have 3 decimal places. In a multi-currency system I take the scale from the currency, or store everything in the smallest unit (long minorUnits);
  • when rounding happens is a business decision: per line or only on the total. It has to be documented, otherwise reports end up with "off by one sum" problems;
  • percentages and exchange rates need more precision: numeric(19,6) or more, and no rounding in intermediate calculations.

In the database I also add constraints like check (amount >= 0), and an FK or a check for the currency. For account (balance) tables, the better approach is not updating the amount but appending entries (a ledger) and computing the total. That is also much better for auditing and for conflicts.