Video in progress
If you leave out @Table and @Column, how does Hibernate choose table and column names?
Those annotations let you set the table and column name, length, nullability and other properties explicitly. If you leave them out, Hibernate derives the names from the class and field names using the naming strategy.
📖 Answer
@Entity
@Table(name = "customers",
uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Customer {
@Id @GeneratedValue
private Long id;
@Column(name = "full_name", nullable = false, length = 120)
private String fullName;
@Column(updatable = false)
private Instant createdAt;
}
In Spring Boot, the default naming strategy turns the field fullName into the column full_name, so in most cases @Column(name=...) isn't needed.
One common mistake: nullable, length and unique affect the DDL only when Hibernate creates the schema itself (ddl-auto=create/update). If Flyway or Liquibase creates your tables, these attributes check nothing at runtime. Put the real constraints in the migration, and do validation with Bean Validation (@NotNull, @Size).
updatable = false and insertable = false, on the other hand, do work at runtime: Hibernate leaves that column out of UPDATE or INSERT.
Sign up to mark studied questions and save your progress.