What is an Entity Class in JPA?
An Entity Class in JPA is a Java class that represents a table in a relational database.
Each object of the entity class represents one row in the database table.
In simple words:
- Entity Class β Database Table
- Entity Object β Table Row
- Class Fields β Table Columns
What Does JPA Mean?
JPA stands for:
Java Persistence API
JPA is used for Object Relational Mapping (ORM) between Java objects and relational databases.
Why Entity Classes are Needed
Without entity classes:
- Developers must write manual SQL queries
- ResultSet mapping becomes difficult
- Database operations require more boilerplate code
Entity classes simplify:
- Database interaction
- CRUD operations
- Relationship mapping
- Data persistence
Simple Real-Time Example
Suppose a database contains:
students
table.
Then we create:
Student.java
entity class to represent that table.
Database Table Example
CREATE TABLE students (
id BIGINT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Entity Class Example
@Entity
@Table(name = "students")
public class Student {
@Id
private Long id;
private String name;
private String email;
public Student() {
}
public Student(
Long id,
String name,
String email) {
this.id = id;
this.name = name;
this.email = email;
}
// getters and setters
}
Important Entity Annotations
| Annotation | Purpose |
|---|---|
| @Entity | Marks class as JPA entity |
| @Table | Maps entity to database table |
| @Id | Marks primary key |
| @GeneratedValue | Auto-generates ID |
| @Column | Maps field to column |
What Does @Entity Mean?
@Entity tells JPA:
βThis class should be mapped to a database table.β
What Does @Table Mean?
@Table specifies the database table name.
Example
@Table(name = "students")
What Happens Without @Table?
If @Table is not specified,
JPA uses the class name as the table name by default.
Example:
Student β student
What Does @Id Mean?
@Id identifies the primary key column.
Primary Key Example
@Id
private Long id;
What is @GeneratedValue?
@GeneratedValue automatically generates primary key values.
Example
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Generation Strategies
| Strategy | Description |
|---|---|
| IDENTITY | Uses auto-increment |
| SEQUENCE | Uses database sequence |
| TABLE | Uses table generator |
| AUTO | Automatically selects strategy |
What is @Column?
@Column maps a field to a specific column.
Example
@Column(name = "student_email")
private String email;
How Entity Mapping Works
- Developer creates entity class
- JPA reads annotations
- Hibernate maps entity to table
- Database operations become automatic
Repository Example
public interface StudentRepository
extends JpaRepository<Student, Long> {
}
Save Entity Example
@Autowired
private StudentRepository repository;
public Student saveStudent() {
Student student = new Student();
student.setName("Naresh");
student.setEmail("naresh@gmail.com");
return repository.save(student);
}
Generated SQL Example
Hibernate automatically generates:
INSERT INTO students(name, email)
VALUES (?, ?)
Fetch Entity Example
public List<Student> getStudents() {
return repository.findAll();
}
Entity Lifecycle in JPA
JPA entities move through different lifecycle states.
Entity Lifecycle States
| State | Description |
|---|---|
| Transient | Object created but not saved |
| Persistent | Object managed by JPA |
| Detached | Object disconnected from session |
| Removed | Object marked for deletion |
Entity Relationships
JPA entities support relationships between tables.
Relationship Types
| Relationship | Description |
|---|---|
| @OneToOne | One record linked to one record |
| @OneToMany | One record linked to many records |
| @ManyToOne | Many records linked to one record |
| @ManyToMany | Many records linked to many records |
One-to-Many Example
@OneToMany(mappedBy = "student")
private List<Course> courses;
Best Practices for Entity Classes
- Always define primary key
- Use meaningful table names
- Keep entities simple
- Use proper relationships
- Avoid unnecessary eager loading
- Use DTOs for API responses when needed
Advantages of Entity Classes
- Automatic database mapping
- Reduces boilerplate code
- Supports relationships
- Simplifies CRUD operations
- Improves maintainability
Disadvantages of Improper Entity Design
- Poor performance
- Complex relationships
- Lazy loading issues
- Large object graphs
Real-Time Example in E-Commerce Application
E-commerce application contains entities such as:
- Product
- Order
- Customer
- Payment
Each entity represents a database table and allows Hibernate to perform database operations automatically.
Common Interview Questions on Entity Class
What is an entity class in JPA?
An entity class is a Java class mapped to a database table.
What does @Entity do?
It marks a class as a JPA entity.
Why is @Id mandatory?
Because every entity must have a primary key.
What is the purpose of @Table?
It maps an entity to a database table.
What is the difference between entity and DTO?
Entity represents database tables, while DTO is used for data transfer between layers.
Entity vs DTO
| Feature | Entity | DTO |
|---|---|---|
| Purpose | Database mapping | Data transfer |
| Mapped to DB | Yes | No |
| Contains Business Data | Yes | Usually limited |
Conclusion
Entity classes are one of the most important concepts in JPA and Hibernate.
They map Java objects to database tables and simplify database operations significantly.
Entity classes help developers:
- Reduce SQL boilerplate code
- Perform automatic CRUD operations
- Manage relationships easily
- Build scalable enterprise applications
Understanding entity classes is essential for Spring Boot developers because modern enterprise applications heavily rely on ORM frameworks for database interaction.