Video in progress
When do you need the @Table and @Column annotations?
When the table or column name (or a property like length or precision) differs from the default. For example, when the table name is a reserved word in SQL, or a column is named differently in a legacy database.
📖 Answer
Without annotations, Hibernate takes the class and field names (in Spring Boot, camelCase -> snake_case): createdAt -> created_at.
@Entity
@Table(name = "orders",
uniqueConstraints = @UniqueConstraint(columnNames = {"customer_id", "number"}))
class Order {
@Id @GeneratedValue
private Long id;
@Column(name = "order_no", nullable = false, length = 32)
private String number;
@Column(precision = 15, scale = 2)
private BigDecimal total;
}
When you need it:
Order->orderis a reserved word in SQL, so we name the tableorders;- the column names in a legacy database are different;
precision/scaleneed to be explicit for money.
A common mistake: nullable = false, length and the like only matter when Hibernate creates the table itself (DDL). On the Java side they validate nothing: null reaches the database and fails there. To validate input you need @NotNull, @Size.
Sign up to mark studied questions and save your progress.