Columns and Data Types

@Column

@Column(name = "product_name", nullable = false, length = 150)
private String name;

@Column(length = 2000)
private String description;

@Column(nullable = false, precision = 10, scale = 2)     // up to 99,999,999.99
private BigDecimal price;

@Column(nullable = false)
private Integer stock = 0;

@Column(unique = true, nullable = false, updatable = false, length = 40)
private String sku;

@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
AttributeMeaning
nameColumn name (default: field name in snake_case with Spring Boot)
nullablefalse adds not null to the DDL
lengthvarchar size for strings (default 255)
precision, scaleTotal digits and digits after the decimal point for BigDecimal
uniqueAdds a unique constraint
insertable, updatablefalse = Hibernate never writes this column in INSERT / UPDATE

Note: nullable, length and unique only affect the generated DDL. They do not validate data in Java. Use Bean Validation (@NotBlank, @Size) for that — see the Spring Boot material.

Java Type to SQL Type

Java typeMySQLPostgreSQL
Long / longbigintbigint
Integer / intintinteger
Stringvarchar(255)varchar(255)
BigDecimaldecimal(p,s)numeric(p,s)
Booleanbitboolean
LocalDatedatedate
LocalDateTimedatetime(6)timestamp(6)
Instant, OffsetDateTimedatetime(6)timestamp(6) with time zone
UUIDbinary(16)uuid
byte[] with @Loblongblobbytea / oid
  • Money: always BigDecimal, never double (0.1 + 0.2 is not 0.3 in floating point).
  • Dates: use java.time types. The old java.util.Date with @Temporal is no longer needed.
  • Wrapper vs primitive: Integer can hold null (unknown); int cannot. Prefer wrappers for ids so a new entity has id == null.

Why BigDecimal for Prices

Example

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        double d = 0.10 + 0.20;
        System.out.println("double:     " + d);

        BigDecimal b = new BigDecimal("0.10").add(new BigDecimal("0.20"));
        System.out.println("BigDecimal: " + b);

        // 3 items at Rs.199.99 with 18% GST
        BigDecimal price = new BigDecimal("199.99");
        BigDecimal total = price.multiply(BigDecimal.valueOf(3))
            .multiply(new BigDecimal("1.18"))
            .setScale(2, java.math.RoundingMode.HALF_UP);
        System.out.println("Total with GST: Rs." + total);
    }
}

Output

double:     0.30000000000000004
BigDecimal: 0.30
Total with GST: Rs.707.96