The @Column annotation helps connect a class field to a specific database column. It tells Spring Boot how to save and read data from the database.
0
0
Column mapping with @Column in Spring Boot
Introduction
When you want to name a database column differently from your class field.
When you want to set rules like column length or if it can be empty.
When you want to control how data is stored, like making a column unique.
When you want to add comments or specify column type in the database.
Syntax
Spring Boot
@Column(name = "column_name", nullable = false, length = 100, unique = true)
name sets the exact database column name.
nullable controls if the column can be empty (true or false).
Examples
This maps the
email field to the user_email column in the database.Spring Boot
@Column(name = "user_email")
private String email;This makes sure
username cannot be empty and limits it to 50 characters.Spring Boot
@Column(nullable = false, length = 50)
private String username;This ensures the
phoneNumber is unique in the database.Spring Boot
@Column(unique = true) private String phoneNumber;
Sample Program
This example shows a User entity where the name field is mapped to the user_name column with rules: it cannot be empty and has max length 100. The email field must be unique in the database.
Spring Boot
import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Column; @Entity public class User { @Id private Long id; @Column(name = "user_name", nullable = false, length = 100) private String name; @Column(unique = true) private String email; // Constructors, getters, setters public User() {} public User(Long id, String name, String email) { this.id = id; this.name = name; this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
OutputSuccess
Important Notes
If you don't use @Column, Spring Boot uses the field name as the column name by default.
Use @Column to avoid mistakes when your database column names differ from your Java fields.
Always check your database schema matches your entity mappings to avoid errors.
Summary
@Column links a Java field to a database column.
You can set column name, length, uniqueness, and nullability.
This helps keep your Java code and database in sync.