Clean ⢠Professional
In Spring Data JPA, @Entity, @Id, and @GeneratedValue are core annotations that form the foundation of ORM (Object-Relational Mapping). They are essential for mapping Java classes to database tables, defining primary keys, and automating ID generation, enabling clean, maintainable, and scalable applications.
Marks a Java class as a JPA entity, meaning it represents a table in the database.
Key Points:
@Entity maps to a database table.@Table(name="table_name").@OneToMany, @ManyToOne, etc.Example:
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")// Optional
publicclassUser {
private Long id;
private String name;
private String email;
// Getters and setters
}
ā
@Entity tells JPA/Hibernate to manage this class as a database table.
Specifies the primary key of an entity.
Key Points:
@Id.@GeneratedValue for automatic generation.Example:
import jakarta.persistence.Id;
@Entity
publicclassUser {
@Id
private Long id;
private String name;
}
ā
@Id ensures JPA knows which field is the unique identifier for each record.
Automatically generates values for the primary key field annotated with @Id.
Generation Strategies:
GenerationType.AUTO ā JPA provider selects the strategy.GenerationType.IDENTITY ā Uses auto-increment columns.GenerationType.SEQUENCE ā Uses a database sequence (common in Oracle, PostgreSQL).GenerationType.TABLE ā Uses a special table to generate IDs.Example:
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@Entity
publicclassUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
ā
@GeneratedValue eliminates the need to manually assign primary key values.
@Entity
@Table(name = "users")
publicclassUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
@Entity ā Marks the class as a table.@Id ā Specifies the primary key column.@GeneratedValue ā Auto-generates the primary key on record insertion.| Annotation | Purpose | Example Usage |
|---|---|---|
@Entity | Marks class as a database table | @Entity |
@Id | Specifies primary key field | @Id |
@GeneratedValue | Auto-generates primary key values | @GeneratedValue(strategy=IDENTITY) |
Using @Entity, @Id, and @GeneratedValue together allows developers to map Java objects to database tables effortlessly. These annotations form the backbone of ORM in Spring Data JPA, reducing boilerplate code, improving maintainability, and enabling rapid development of enterprise-grade applications.