The @Entity
annotation marks a Java class as a persistent entity in JPA/Hibernate, meaning it should be mapped to a table in the database.
It tells the JPA provider (Hibernate) to manage instances of the class as rows in a relational table.
🔹 What does @Entity
do?
✅ Registers the class as part of the persistence context → Hibernate will map it to a database table.
✅ Enables automatic ORM (object-relational mapping) → Hibernate translates Java objects into SQL statements for CRUD operations.
✅ Ensures the class participates in JPA features like transactions, caching, dirty checking, and queries.
🔹 Basic example:
import javax.persistence.Entity;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
}
✅ Here:
User
is an entity → each instance ofUser
corresponds to a row in a table (e.g.,users
).- Fields in
User
map to columns in the table.
🔹 Important notes:
✅ Every @Entity
class must have a primary key, defined with @Id
.
✅ You can specify a custom table name with @Table(name = "your_table")
, but if omitted, the table defaults to the class name.
🔹 Why is it important?
Without @Entity
, Hibernate/JPA ignores the class → it won’t be mapped to a table, persisted, or managed.
✅ Key takeaway:@Entity
marks a Java class as a persistent entity mapped to a database table, enabling Hibernate or any JPA provider to manage it automatically.