What is the purpose of the @Table annotation in Spring Data JPA?
A) To specify the primary key column
B) To map the entity to a specific database table
C) To define the database schema
D) To configure caching for the entity
Answer:
B) To map the entity to a specific database table
Explanation:
The @Table
annotation in Spring Data JPA is used to map an entity class to a specific database table. This annotation is optional, but it is useful when the table name in the database differs from the entity class name.
For example:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and setters
}
In this example, the @Table(name = "users")
annotation specifies that the User
entity should be mapped to the “users” table in the database. Without this annotation, JPA would assume that the table name is the same as the entity class name (“User”).
The @Table
annotation is especially useful in scenarios where table names need to adhere to specific naming conventions or when multiple entities map to tables with similar names but different suffixes or prefixes.