Java.Hibernate.Beginner.What does the @Table annotation do?

The @Table annotation in JPA/Hibernate is used in combination with @Entity to customize the mapping between your Java class and the database table.
It allows you to explicitly specify the table name and define additional table-level constraints like unique keys or indexes.


🔹 What happens if you omit @Table?
✅ By default, JPA maps the entity to a table with the same name as the class (e.g., class User → table User).


🔹 How to use @Table:

@Entity
@Table(name = "users") // customize table name
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
}

✅ Here:

  • Even if the Java class is named User, the entity will be stored in the users table.

🔹 Advanced features of @Table:
You can also define unique constraints or indexes:

@Entity
@Table(
    name = "users",
    uniqueConstraints = @UniqueConstraint(columnNames = {"email"}),
    indexes = @Index(name = "idx_username", columnList = "username")
)
public class User {
    @Id
    private Long id;
    private String username;
    private String email;
}

✅ Here:

  • Adds a unique constraint on email.
  • Creates an index on username.

🔹 Key options in @Table:

  • name → database table name.
  • catalog and schema → specify catalog/schema in DB (optional).
  • uniqueConstraints → declare unique constraints on one or more columns.
  • indexes → define database indexes (JPA 2.1+).

🔹 Key points:
@Entity alone maps the class → @Table customizes how it maps to the physical table.
✅ Without @Table, the default table name is the class

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.