Skip to lesson

Enums, dates and BigDecimal fields

A table column holds only simple values, but ShopLite's entities use richer types: an order status, a time, a price. Each needs the right mapping, or the saved data comes back changed.

@Enumerated(EnumType.STRING) for OrderStatus

EnumType.STRING stores an enum constant by its name, so OrderStatus.SHIPPED becomes the text 'SHIPPED' in the column. EnumType.ORDINAL stores its position instead, which changes meaning when constants are reordered.

@Enumerated(EnumType.STRING) stores the constant's name. ShopLite's orders.status is a VARCHAR(10) with a CHECK for the four names, so Example 1 maps OrderStatus that way.

Example 1 · src/main/java/com/shoplite/order/Order.java with OrderStatus

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

OrderStatus.javaJava
// src/main/java/com/shoplite/order/OrderStatus.javapackage com.shoplite.order;
public enum OrderStatus {    PLACED, SHIPPED, DELIVERED, CANCELLED}
// src/main/java/com/shoplite/order/Order.javapackage com.shoplite.order;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.EnumType;import jakarta.persistence.Enumerated;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
import java.time.LocalDateTime;
@Entity@Table(name = "orders")                 // "order" is an SQL keyword, so the table is "orders"public class Order {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "order_id")    private Integer id;
    @Column(name = "customer_id", nullable = false)    private Integer customerId;
    @Column(name = "address_id", nullable = false)    private Integer addressId;
    @Enumerated(EnumType.STRING)    @Column(nullable = false, length = 10)    private OrderStatus status;
    @Column(name = "ordered_at", nullable = false)    private LocalDateTime orderedAt;
    protected Order() {    }
    public Order(Integer customerId, Integer addressId, LocalDateTime orderedAt) {        this.customerId = customerId;        this.addressId = addressId;        this.status = OrderStatus.PLACED;        this.orderedAt = orderedAt;    }
    public Integer getId() { return id; }    public Integer getCustomerId() { return customerId; }    public Integer getAddressId() { return addressId; }    public OrderStatus getStatus() { return status; }    public LocalDateTime getOrderedAt() { return orderedAt; }
    public void ship() {        this.status = OrderStatus.SHIPPED;    }}
package com.shoplite.order;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Componentclass OrderDemoRunner implements CommandLineRunner {
    private final OrderRepository orders;
    OrderDemoRunner(OrderRepository orders) {        this.orders = orders;    }
    @Override    public void run(String... args) {        Order order14 = orders.findById(14).orElseThrow();        System.out.println("Order 14: " + order14.getStatus() + " at " + order14.getOrderedAt());
        Order placed = new Order(8, 8, LocalDateTime.of(2026, 10, 16, 11, 42));        orders.save(placed);        System.out.println("New order " + placed.getId() + ": " + placed.getStatus());
        if (order14.getStatus() == OrderStatus.SHIPPED) {            System.out.println("Order 14 can be delivered next");        }    }}
Sample output
DEBUG ... org.hibernate.SQL                        : select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
Order 14: SHIPPED at 2026-09-21T21:05
DEBUG ... org.hibernate.SQL                        : insert into orders (address_id,customer_id,ordered_at,status) values (?,?,?,?)
New order 17: PLACED
Order 14 can be delivered next

What this code does

  • The text 'SHIPPED' in the table became the constant OrderStatus.SHIPPED, so the runner compares with == and never with strings.
  • The new order sends the name PLACED in the INSERT. The constructor sets it, so no caller can create an order in another state.
  • ordered_at came back as 2026-09-21T21:05, the same wall-clock time as in the table, because LocalDateTime has no time zone to convert.

Example 2 · Why ORDINAL corrupts data when constants are reordered

OrdinalTrapDemo.javaJava
import java.util.List;
// Version 1 of the app: the order of the constants decides the ordinal numbersenum StatusV1 { PLACED, SHIPPED, DELIVERED, CANCELLED }
// Version 2: a developer adds PACKED in the middle, where it "belongs"enum StatusV2 { PLACED, PACKED, SHIPPED, DELIVERED, CANCELLED }
public class OrdinalTrapDemo {
    public static void main(String[] args) {        List<StatusV1> saved = List.of(StatusV1.SHIPPED, StatusV1.DELIVERED, StatusV1.CANCELLED);
        System.out.println("Saved by version 1 -> read by version 2");        for (StatusV1 status : saved) {            int asOrdinal = status.ordinal();          // what EnumType.ORDINAL stores            String asName = status.name();
            StatusV2 fromOrdinal = StatusV2.values()[asOrdinal];            StatusV2 fromName = StatusV2.valueOf(asName);            System.out.println(status + ": ORDINAL " + asOrdinal + " -> " + fromOrdinal                    + ", STRING '" + asName + "' -> " + fromName);        }    }}
Output
Saved by version 1 -> read by version 2
SHIPPED: ORDINAL 1 -> PACKED, STRING 'SHIPPED' -> SHIPPED
DELIVERED: ORDINAL 2 -> SHIPPED, STRING 'DELIVERED' -> DELIVERED
CANCELLED: ORDINAL 3 -> DELIVERED, STRING 'CANCELLED' -> CANCELLED

What this code does

  • A plain-Java model of what JPA does: ordinal() is the number EnumType.ORDINAL stores, name() is the text EnumType.STRING stores, and values()[n] / valueOf(text) are how each is read back.
  • After PACKED was added in the middle, every old number points one constant too early: a cancelled order now reads as delivered. With names, every row still reads correctly.
  • Renaming a constant is the one change that breaks STRING (the old text no longer matches). Treat enum names as part of the data, like column names.

Without @Enumerated, JPA uses EnumType.ORDINAL: the constant's position, 0 for the first, 1 for the second, so the numbers depend on the order you wrote the constants in. Add PACKED between PLACED and SHIPPED one day, and every stored 1 that meant SHIPPED now reads as PACKED (Example 2). Nothing fails; the data is silently wrong.

On ShopLite, forgetting @Enumerated is at least caught at startup: ORDINAL expects a number column, so validate stops with found [varchar (Types#VARCHAR)], but expecting [tinyint (Types#TINYINT)].

Predict the output

What goes into the status column?

Read the mapping, then pick what the database holds.

Round 1 of 3

SHIPPED is saved with no @Enumerated. What is stored?

enum OrderStatus { PLACED, SHIPPED, DELIVERED, CANCELLED }
@Column(nullable = false)
private OrderStatus status;
If Hibernate creates the table itself, it writes status enum ('CANCELLED','DELIVERED','PLACED','SHIPPED') for a STRING enum on MySQL. It still validates fine against ShopLite's VARCHAR(10).

Dates and times: LocalDateTime, LocalDate and Instant

A LocalDateTime is a date and a clock time with no time zone, exactly like a MySQL DATETIME. It maps with no extra annotation, and 21:05 in the table is 21:05 in Java.

LocalDateTime maps straight to a DATETIME column. Example 3 shows what goes wrong when an Instant is used on an India-time column instead.

Example 3 · The Instant trap on an India-time DATETIME column

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Java
// Customer, mapped two ways (the table holds 2026-06-02 09:05:00, India time)@Column(name = "created_at", insertable = false, updatable = false)private LocalDateTime createdAt;      // run 1
@Column(name = "created_at", insertable = false, updatable = false)private Instant createdAt;            // run 2
Customer meena = customers.findById(3).orElseThrow();System.out.println("Loaded: " + meena.getFullName() + ", phone " + meena.getPhone()        + ", since " + meena.getCreatedAt());
Sample output
Run 1 (LocalDateTime):
Loaded: Meena Iyer, phone null, since 2026-06-02T09:05

Run 2 (Instant):
Loaded: Meena Iyer, phone null, since 2026-06-02T09:05:00Z

What this code does

  • Both runs passed validation, so nothing warned us. LocalDateTime shows the wall-clock time stored in the table.
  • Instant read the same 09:05 as 09:05Z, a moment in UTC, which is 14:35 in India. In our test the result stayed the same with the JVM in UTC and with hibernate.jdbc.time_zone set, because Hibernate 7 treats Instant as UTC on MySQL.
  • Rule for ShopLite: DATETIME columns hold India time and map to LocalDateTime; the API adds +05:30 when it writes JSON.

java.time types map directly: LocalDateTime for DATETIME, LocalDate for DATE, LocalTime for TIME. The old @Temporal annotation was only for java.util.Date and Calendar; you do not need it. ShopLite's DATETIME columns hold India time, so ordered_at maps to LocalDateTime orderedAt.

An Instant is one moment on the world's timeline, always shown in UTC (the Z at the end). Hibernate 7 on MySQL stores and reads an Instant as UTC. Map ShopLite's India-time created_at to an Instant and Meena's 09:05 India time comes back as 09:05Z, which is 14:35 in India: five and a half hours wrong (Example 3). Use Instant only for columns that really hold UTC.

BigDecimal for money: precision 10, scale 2

BigDecimal is a Java class that stores a decimal number exactly, digit by digit. Money fields use it with a DECIMAL(10,2) column, because a double cannot hold most decimal fractions exactly.

With BigDecimal, 399.90 + 399.90 + 399.90 is exactly 1199.70. Example 4 adds the same prices as a double and as a BigDecimal.

Example 4 · double vs BigDecimal for a shopping cart

MoneyTypesDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;
public class MoneyTypesDemo {
    public static void main(String[] args) {        // A cart: three T-shirts at Rs 399.90 each, with double        double cart = 0;        for (int i = 0; i < 3; i++) {            cart += 399.90;        }        System.out.println("double total:     " + cart);        System.out.println("equals 1199.70?   " + (cart == 1199.70));
        // The same cart with BigDecimal, built from a String        BigDecimal exact = BigDecimal.ZERO;        for (int i = 0; i < 3; i++) {            exact = exact.add(new BigDecimal("399.90"));        }        System.out.println("BigDecimal total: " + exact);
        // Traps inside BigDecimal itself        System.out.println("new BigDecimal(0.1): " + new BigDecimal(0.1));        System.out.println("BigDecimal.valueOf(0.1): " + BigDecimal.valueOf(0.1));        BigDecimal a = new BigDecimal("17999.00");        BigDecimal b = new BigDecimal("17999.0");        System.out.println("equals: " + a.equals(b) + ", compareTo: " + a.compareTo(b));
        BigDecimal gst = new BigDecimal("849.00").multiply(new BigDecimal("0.18"))                .setScale(2, RoundingMode.HALF_UP);        System.out.println("GST: " + gst);    }}
Output
double total:     1199.6999999999998
equals 1199.70?   false
BigDecimal total: 1199.70
new BigDecimal(0.1): 0.1000000000000000055511151231257827021181583404541015625
BigDecimal.valueOf(0.1): 0.1
equals: false, compareTo: 0
GST: 152.82

What this code does

  • Three T-shirts at Rs 399.90 with double add up to 1199.6999999999998, and a check against 1199.70 fails. The BigDecimal cart is exact and keeps two decimals.
  • new BigDecimal(0.1) copies the binary error of the double 0.1; BigDecimal.valueOf(0.1) and new BigDecimal("0.1") give the value you meant.
  • equals says 17999.00 and 17999.0 differ because their scales differ; compareTo returns 0, so use it for "same amount". GST is rounded to paise with setScale(2, RoundingMode.HALF_UP).

A double stores numbers in binary, so the same sum gives 1199.6999999999998 (Example 4), and a paisa lost per bill is a real bug. Map a DECIMAL(10,2) column as @Column(nullable = false, precision = 10, scale = 2) private BigDecimal price;. A double field against a DECIMAL column fails validation (previous lesson).

Three BigDecimal rules:

  • Create values from a String (new BigDecimal("399.90")) or BigDecimal.valueOf, never new BigDecimal(0.1).
  • Compare with compareTo, because equals also compares the scale (17999.00 is not equals to 17999.0).
  • Round with setScale(2, RoundingMode.HALF_UP) when you multiply, as for GST.
MySQL rounds extra decimals silently: saving 499.999 into DECIMAL(10,2) stored 500.00 (Example 5). The API contract rejects prices with more than two decimals with a 400, so the DTO must check it; the database will not.

BOOLEAN columns like is_active

A MySQL BOOLEAN is really TINYINT(1), and a Java boolean field maps to it directly. The snippet maps is_active to a field named active.

Java
@Column(name = "is_active", nullable = false)private boolean active = true;        // new products start active, like the column DEFAULT TRUE
public boolean isActive() { return active; }
public void deactivate() {            // a business method, not setActive(...)    this.active = false;}

Example 5 · Product: BigDecimal price and the is_active flag

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Product.javaJava
// src/main/java/com/shoplite/product/Product.javapackage com.shoplite.product;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity@Table(name = "products")public class Product {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "product_id")    private Integer id;
    @Column(nullable = false, length = 20, unique = true)    private String sku;
    @Column(nullable = false, length = 120)    private String name;
    @Column(name = "category_id", nullable = false)    private Integer categoryId;
    @Column(nullable = false, precision = 10, scale = 2)    private BigDecimal price;
    @Column(nullable = false)    private int stock;
    @Column(name = "is_active", nullable = false)    private boolean active = true;
    protected Product() {    }
    public Product(String sku, String name, Integer categoryId, BigDecimal price, int stock) {        this.sku = sku;        this.name = name;        this.categoryId = categoryId;        this.price = price;        this.stock = stock;    }
    public Integer getId() { return id; }    public String getSku() { return sku; }    public String getName() { return name; }    public BigDecimal getPrice() { return price; }    public int getStock() { return stock; }    public boolean isActive() { return active; }
    public void deactivate() {        this.active = false;    }}
// src/main/java/com/shoplite/product/ProductDemoRunner.javapackage com.shoplite.product;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import java.math.BigDecimal;import java.math.RoundingMode;
@Componentclass ProductDemoRunner implements CommandLineRunner {
    private final ProductRepository products;
    ProductDemoRunner(ProductRepository products) {        this.products = products;    }
    @Override    public void run(String... args) {        Product cable = products.findById(15).orElseThrow();        System.out.println(cable.getSku() + " active? " + cable.isActive());
        Product kurta = products.findById(12).orElseThrow();        BigDecimal threeKurtas = kurta.getPrice().multiply(BigDecimal.valueOf(3));        BigDecimal gst = threeKurtas.multiply(new BigDecimal("0.05")).setScale(2, RoundingMode.HALF_UP);        System.out.println("3 x " + kurta.getPrice() + " = " + threeKurtas + ", GST 5% = " + gst);
        Product mouse = new Product("ACC-MS200", "Zebronics Wireless Mouse", 4, new BigDecimal("499.999"), 15);        products.save(mouse);        Product reloaded = products.findById(mouse.getId()).orElseThrow();        System.out.println("Saved 499.999, stored " + reloaded.getPrice() + ", active " + reloaded.isActive());    }}
Sample output
DEBUG ... org.hibernate.SQL                        : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
ACC-USBC1 active? false
DEBUG ... org.hibernate.SQL                        : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
3 x 899.00 = 2697.00, GST 5% = 134.85
DEBUG ... org.hibernate.SQL                        : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?)
DEBUG ... org.hibernate.SQL                        : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
Saved 499.999, stored 500.00, active true

What this code does

  • Product 15, the USB-C cable, has is_active = FALSE in the seed data, and the boolean active field reads it as false.
  • The kurta's price arrives as 899.00 with its two decimals, so arithmetic and printing need no formatting tricks.
  • Now the INSERT sends is_active too (true from the field initialiser). The price 499.999 was rounded by MySQL to 500.00 with no error: check the scale in the request DTO.

The naming needs care. A field isActive maps to is_active by snake case, but its getter would read isIsActive(). ShopLite names the field active, maps the column with @Column(name = "is_active") and gets the natural getter isActive(). The same goes for is_default and defaultAddress.

Use primitive boolean for NOT NULL columns: it can never be null, and a field initialiser (= true) gives new products the same default the table has.

An AttributeConverter for a custom type: Pincode as CHAR(6)

An AttributeConverter<X, Y> tells JPA how to turn your own Java type X into a column value of type Y and back, with convertToDatabaseColumn and convertToEntityAttribute.

A pincode is not just any String. Example 6 wraps it in a Pincode type whose constructor checks the rule, and stores it as CHAR(6).

Example 6 · Pincode, PincodeConverter and the Address entity

Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)

Pincode.javaJava
// src/main/java/com/shoplite/common/Pincode.javapackage com.shoplite.common;
/** An Indian postal code: exactly 6 digits, not starting with 0. */public record Pincode(String value) {
    public Pincode {        if (value == null || !value.matches("[1-9][0-9]{5}")) {            throw new IllegalArgumentException("Invalid pincode: " + value);        }    }
    @Override    public String toString() {        return value;    }}
// src/main/java/com/shoplite/common/PincodeConverter.javapackage com.shoplite.common;
import jakarta.persistence.AttributeConverter;import jakarta.persistence.Converter;
@Converter(autoApply = true)          // used for every Pincode field in every entitypublic class PincodeConverter implements AttributeConverter<Pincode, String> {
    @Override    public String convertToDatabaseColumn(Pincode pincode) {        return pincode == null ? null : pincode.value();    }
    @Override    public Pincode convertToEntityAttribute(String column) {        return column == null ? null : new Pincode(column);    }}
@Column(nullable = false, length = 6)private Pincode pincode;
Address home = addresses.findById(1).orElseThrow();Pincode pin = home.getPincode();System.out.println(home.getCity() + " " + pin + " (" + pin.getClass().getSimpleName() + "), default " + home.isDefaultAddress());
Address hostel = new Address(8, "Hostel", "Block C, IIT Bombay", "Mumbai", "Maharashtra", new Pincode("400076"));addresses.save(hostel);System.out.println("Saved address " + hostel.getId() + " with pincode " + hostel.getPincode());
try {    new Pincode("040007");} catch (IllegalArgumentException e) {    System.out.println(e.getMessage());}
Sample output
DEBUG ... org.hibernate.SQL                        : select a1_0.address_id,a1_0.city,a1_0.customer_id,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.pincode,a1_0.state from addresses a1_0 where a1_0.address_id=?
Bengaluru 560038 (Pincode), default true
DEBUG ... org.hibernate.SQL                        : insert into addresses (city,customer_id,is_default,label,line1,pincode,state) values (?,?,?,?,?,?,?)
Saved address 10 with pincode 400076
Invalid pincode: 040007

What this code does

  • The SELECT reads pincode as text and convertToEntityAttribute turns it into a Pincode; the INSERT sends "400076" through convertToDatabaseColumn.
  • The record's compact constructor rejects 040007, so an invalid pincode cannot exist anywhere in the program, not just in the database.
  • CHAR(6) passed validation against the converter's String side; no columnDefinition was needed.

As a Pincode record, its constructor checks the rule (6 digits, not starting with 0) once, and the rest of the code can trust every Pincode it gets. The column stays a plain CHAR(6).

@Converter(autoApply = true) applies the converter to every Pincode field in every entity, with no annotation on the fields. Without autoApply, put @Convert(converter = PincodeConverter.class) on each field. Handle null in both methods, because nullable columns pass null through.

Next step

Check your understanding

12 quick questions