0
0
SpringbootConceptBeginner · 3 min read

@Table Annotation in Spring Boot: What It Is and How to Use

The @Table annotation in Spring Boot is used to specify the database table that a Java entity class maps to. It helps define the table name and schema details when using JPA with Spring Data.
⚙️

How It Works

The @Table annotation works like a label that tells Spring Boot which database table a Java class should connect to. Imagine you have a spreadsheet where each sheet is a table, and each row is a record. The entity class is like a template for each row, and @Table points to the exact sheet (table) where the data lives.

When you use Spring Data JPA, it automatically reads this annotation to know where to save or find data. If you don't specify @Table, Spring assumes the table name matches the class name. But with @Table, you can customize this to match your database exactly.

💻

Example

This example shows a simple entity class mapped to a database table named users using @Table.

java
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "users")
public class User {
    @Id
    private Long id;
    private String name;

    // getters and setters
    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; }
}
Output
No direct output; this maps the User class to the 'users' table in the database.
🎯

When to Use

Use @Table when your database table name is different from your Java class name or when you want to specify the schema or catalog. For example, if your class is named Customer but the table is called client_data, @Table(name = "client_data") tells Spring Boot where to look.

This is common in real projects where database naming conventions differ from Java naming. It also helps when working with legacy databases or multiple schemas.

Key Points

  • @Table defines the database table for an entity class.
  • It allows customizing table name, schema, and catalog.
  • If omitted, the table name defaults to the entity class name.
  • Works with @Entity in JPA for ORM mapping.

Key Takeaways

@Table links a Java entity class to a specific database table.
Use @Table(name = "table_name") to customize the table name.
It is essential when database table names differ from class names.
Works together with @Entity to enable ORM in Spring Boot.