@Entity Annotation
- The
@Entityannotation is used in JPA to specify that a particular class is an entity. - An entity represents a table in a relational database, and each instance of the entity corresponds to a row in that table.
- By marking a class with the
@Entityannotation, JPA will treat it as a database table and handle the mapping of the class’s fields to the corresponding table columns.
Key Roles of @Entity:
- Identification:
- It tells JPA that the class is an entity and that it should be mapped to a corresponding database table.
- Mapping to Database:
- Establishes a mapping between the Java class and the database table, where each instance of the entity corresponds to a row in the table.
- Lifecycle Management:
- Enables the JPA provider to manage the lifecycle of the entity instances, including persistence, removal, and updates.
Example Usage:
import javax.persistence.Entity; import javax.persistence.Id; @Entitypublic class User {
@Id
private Long id;
private String name;
private String email;
// Getters and setters
}
In this example:
- The @Entity annotation marks the User class as an entity.
- Instances of User will be mapped to a database table (usually named user by default).
- The @Id annotation specifies the primary key of the entity.