Careeroza
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;| Attribute | Meaning |
|---|---|
name | Column name (default: field name in snake_case with Spring Boot) |
nullable | false adds not null to the DDL |
length | varchar size for strings (default 255) |
precision, scale | Total digits and digits after the decimal point for BigDecimal |
unique | Adds a unique constraint |
insertable, updatable | false = 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 type | MySQL | PostgreSQL |
|---|---|---|
Long / long | bigint | bigint |
Integer / int | int | integer |
String | varchar(255) | varchar(255) |
BigDecimal | decimal(p,s) | numeric(p,s) |
Boolean | bit | boolean |
LocalDate | date | date |
LocalDateTime | datetime(6) | timestamp(6) |
Instant, OffsetDateTime | datetime(6) | timestamp(6) with time zone |
UUID | binary(16) | uuid |
byte[] with @Lob | longblob | bytea / oid |
- Money: always
BigDecimal, neverdouble(0.1 + 0.2 is not 0.3 in floating point). - Dates: use
java.timetypes. The oldjava.util.Datewith@Temporalis no longer needed. - Wrapper vs primitive:
Integercan holdnull(unknown);intcannot. Prefer wrappers for ids so a new entity hasid == 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