Entity Relationships
All Java Topics
Last updated: May 25, 2026
Author: ManaCoding Team
Entity relationships in JPA/Hibernate define how tables are connected in a relational database using annotations like OneToOne, OneToMany, ManyToOne, and ManyToMany.
Syntax
@OneToMany(mappedBy = "user") private List<Order> orders; @ManyToOne private User user;
Example Program
import jakarta.persistence.*;
import java.util.*;
@Entity
class User {
@Id
private int id;
private String name;
@OneToMany(mappedBy = "user")
private List<Order> orders;
}
@Entity
class Order {
@Id
private int id;
private String product;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
public class Main {
public static void main(String[] args) {
System.out.println("Entity Relationships Example");
}
}
// Output:
// Entity Relationships Example
What are Entity Relationships?
- 1 Define relationships between database tables.
- 2 Implemented using JPA annotations.
- 3 Represent real-world associations.
- 4 Used in ORM mapping.
Types of Relationships
- 1 One-to-One (@OneToOne)
- 2 One-to-Many (@OneToMany)
- 3 Many-to-One (@ManyToOne)
- 4 Many-to-Many (@ManyToMany)
Example Use Cases
- 1 User → Orders (One-to-Many)
- 2 Employee → Department (Many-to-One)
- 3 Student → Courses (Many-to-Many)
- 4 User → Profile (One-to-One)
Why Relationships Matter?
- 1 Represent real-world data structure.
- 2 Enable relational database design.
- 3 Improve data consistency.
- 4 Support complex queries.
Quick Summary
- Entity relationships define table connections.
- JPA supports OneToOne, OneToMany, ManyToOne, ManyToMany.
- Used in ORM frameworks like Hibernate.
- Important for database design.
FAQs
What is @OneToMany relationship?
One entity is linked to multiple entities.
What is @ManyToOne relationship?
Many entities are linked to one entity.
What is mappedBy used for?
It defines the owning side of relationship.
What is @ManyToMany relationship?
Multiple entities are linked to multiple entities.
Why use entity relationships?
To model real-world data associations.
Interview Questions
Q1.
What is @OneToMany relationship?
Answer:
One entity is linked to multiple entities.
Q2.
What is @ManyToOne relationship?
Answer:
Many entities are linked to one entity.
Q3.
What is mappedBy used for?
Answer:
It defines the owning side of relationship.
Q4.
What is @ManyToMany relationship?
Answer:
Multiple entities are linked to multiple entities.
Q5.
Why use entity relationships?
Answer:
To model real-world data associations.
Quiz
Which annotation is used for One-to-Many relationship?