What is @OneToMany Mapping in JPA?
@OneToMany is a JPA annotation used to define a one-to-many relationship between two entity classes.
It means:
βOne record in one table can be associated with multiple records in another table.β
In simple words:
- One entity β Many related entities
- One database row β Multiple related rows
Real-Life Example of One-to-Many Relationship
Common examples:
- One customer can place many orders
- One department can have many employees
- One student can enroll in many courses
Database Example
customers Table
| id | name |
|---|---|
| 1 | Naresh |
orders Table
| id | product | customer_id |
|---|---|---|
| 101 | Laptop | 1 |
| 102 | Mobile | 1 |
Here:
- One customer has many orders
- Each order belongs to one customer
Why @OneToMany Mapping is Needed
Without relationship mapping:
- Developers must manually write JOIN queries
- Object navigation becomes difficult
- Large SQL code increases complexity
@OneToMany simplifies:
- Relationship handling
- Automatic joins
- Object navigation
- Data fetching
Basic @OneToMany Example
Customer Entity
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany
@JoinColumn(name = "customer_id")
private List<Order> orders;
}
Order Entity
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String product;
}
What Does @JoinColumn Mean?
@JoinColumn specifies the foreign key column
used to establish the relationship.
Example
@JoinColumn(name = "customer_id")
means:
customer_id
is the foreign key column in the orders table.
Generated Database Structure
orders Table
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
product VARCHAR(255),
customer_id BIGINT,
FOREIGN KEY (customer_id)
REFERENCES customers(id)
)
How @OneToMany Works Internally
- Hibernate detects relationship annotations
- Foreign key mapping is created
- JOIN queries are generated automatically
- Related entities are fetched when required
Saving One-to-Many Data
Order order1 = new Order();
order1.setProduct("Laptop");
Order order2 = new Order();
order2.setProduct("Mobile");
Customer customer = new Customer();
customer.setName("Naresh");
customer.setOrders(
List.of(order1, order2)
);
customerRepository.save(customer);
Generated SQL Example
INSERT INTO customers(name)
VALUES ('Naresh');
INSERT INTO orders(product, customer_id)
VALUES ('Laptop', 1);
INSERT INTO orders(product, customer_id)
VALUES ('Mobile', 1);
Fetch Data Example
Customer customer =
customerRepository.findById(1L).get();
List<Order> orders =
customer.getOrders();
Types of One-to-Many Mapping
JPA supports:
- Unidirectional mapping
- Bidirectional mapping
1. Unidirectional One-to-Many Mapping
Only one entity knows about the relationship.
Example
@OneToMany
private List<Order> orders;
Customer knows orders, but Order does not know customer.
2. Bidirectional One-to-Many Mapping
Both entities know about each other.
Bidirectional Example
Customer Entity
@Entity
public class Customer {
@Id
private Long id;
@OneToMany(mappedBy = "customer")
private List<Order> orders;
}
Order Entity
@Entity
public class Order {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
}
What Does mappedBy Mean?
mappedBy specifies:
- The inverse side of the relationship
- Which entity owns the relationship
Owning Side vs Inverse Side
| Type | Description |
|---|---|
| Owning Side | Contains @JoinColumn |
| Inverse Side | Contains mappedBy |
Fetch Types in @OneToMany
JPA supports:
- LAZY fetching
- EAGER fetching
LAZY Fetch Example
@OneToMany(fetch = FetchType.LAZY)
Related data loads only when accessed.
EAGER Fetch Example
@OneToMany(fetch = FetchType.EAGER)
Related data loads immediately.
LAZY vs EAGER Fetching
| Feature | LAZY | EAGER |
|---|---|---|
| Loading Time | On demand | Immediate |
| Performance | Better | Can be slower |
| Memory Usage | Lower | Higher |
Cascade Types in @OneToMany
Cascade operations automatically apply actions to related entities.
Cascade Example
@OneToMany(
cascade = CascadeType.ALL
)
What CascadeType.ALL Does
When Customer is saved:
- Orders are also saved automatically
Orphan Removal Example
Orphan removal deletes child entities automatically.
@OneToMany(
orphanRemoval = true
)
Advantages of @OneToMany Mapping
- Simplifies relationship handling
- Automatic JOIN queries
- Easy object navigation
- Reduces manual SQL
- Improves maintainability
Disadvantages of Improper One-to-Many Mapping
- N+1 query problem
- Performance issues
- Excessive eager loading
- Large object graphs
What is N+1 Query Problem?
N+1 problem occurs when:
- One query fetches parent entities
- Additional queries fetch child entities repeatedly
This can reduce application performance.
Best Practices for @OneToMany
- Prefer LAZY fetching
- Use pagination for large collections
- Use cascade carefully
- Avoid unnecessary bidirectional mapping
- Optimize JOIN queries
Real-Time Example in E-Commerce Application
E-commerce application may contain:
- One customer β Many orders
- One category β Many products
- One order β Many order items
These relationships are implemented using:
@OneToMany
Difference Between @OneToMany and @ManyToOne
| Feature | @OneToMany | @ManyToOne |
|---|---|---|
| Relationship | One parent β Many children | Many children β One parent |
| Example | Customer β Orders | Order β Customer |
| Collection Used | List/Set | Single object |
Common Interview Questions on @OneToMany
What is @OneToMany mapping?
It defines a one-to-many relationship between entities.
What is mappedBy?
It specifies the inverse side of the relationship.
What is the default fetch type for @OneToMany?
LAZY.
What is CascadeType.ALL?
It applies all persistence operations to child entities automatically.
What is the N+1 query problem?
It occurs when multiple extra queries are executed while fetching related data.
Conclusion
@OneToMany is one of the most important relationship annotations
in JPA and Hibernate.
It helps developers:
- Map parent-child relationships
- Simplify object navigation
- Reduce manual SQL joins
- Build scalable enterprise applications
Understanding @OneToMany is essential for Spring Boot developers
because enterprise applications heavily depend on relational database mappings
for proper data management and scalability.