JPA Entity Relationships Interview Questions and Answers

Master JPA entity relationships with 10 interview questions covering One-to-One, One-to-Many, Many-to-One, Many-to-Many, mappedBy, owning side, cascade, orphan removal, lazy loading, and production best practices.


Introduction

Entity relationships are one of the most frequently asked topics in Java, Spring Boot, Hibernate, and JPA interviews. In enterprise applications, tables rarely exist independently. Customers own accounts, orders contain products, employees belong to departments, and students enroll in courses.

JPA provides annotations to model these relationships directly in Java while Hibernate maps them to foreign keys and join tables in the database.


Relationship Types

flowchart TD
    A[JPA Entity Relationships]

    A --> B[One-to-One]
    A --> C[One-to-Many]
    A --> D[Many-to-One]
    A --> E[Many-to-Many]

Q1. What are Entity Relationships in JPA?

Answer

Entity relationships define how two entities are connected.

JPA automatically manages these relationships using foreign keys.

Relationship Types

Relationship Example
One-to-One Person → Passport
One-to-Many Customer → Orders
Many-to-One Employee → Department
Many-to-Many Student → Course

Banking Example

flowchart LR
Customer --> Account
Account --> Transaction
Customer --> Card

Example

@Entity
class Customer {

    @Id
    Long id;

    @OneToMany(mappedBy = "customer")
    List<Order> orders;
}

Interview Tip

Relationships should represent real business associations rather than database implementation details.


Q2. What is @OneToOne?

Answer

One entity is associated with exactly one other entity.

Example:

  • Person → Passport
  • Employee → Locker
  • User → Profile

Database

PERSON
------
id

PASSPORT
---------
id
person_id

Diagram

flowchart LR
Person --> Passport

Example

@Entity
class Passport {

    @Id
    Long id;

    @OneToOne
    @JoinColumn(name = "person_id")
    Person person;
}

Best Practice

Use One-to-One only when the relationship is truly unique.


Q3. What is @OneToMany?

Answer

One parent owns multiple child records.

Examples:

  • Customer → Orders
  • Department → Employees
  • Order → Items

Diagram

flowchart LR
Customer --> Order1
Customer --> Order2
Customer --> Order3

Example

@Entity
class Customer {

    @Id
    Long id;

    @OneToMany(mappedBy = "customer")
    List<Order> orders;
}

Child Entity

@Entity
class Order {

    @Id
    Long id;

    @ManyToOne
    Customer customer;
}

Database

CUSTOMER
---------
id

ORDER
------
id
customer_id

Q4. What is @ManyToOne?

Answer

Many child records belong to one parent.

Examples

  • Employees → Department
  • Orders → Customer
  • Transactions → Account

Diagram

flowchart LR
Employee1 --> Department
Employee2 --> Department
Employee3 --> Department

Example

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;

Why LAZY?

Large applications may have thousands of child records.

Loading the parent every time wastes memory.


Q5. What is @ManyToMany?

Answer

Many entities are associated with many other entities.

Examples

  • Students ↔ Courses
  • Users ↔ Roles
  • Doctors ↔ Patients

Diagram

flowchart LR
Student1 --> CourseA
Student1 --> CourseB
Student2 --> CourseA

Join Table

STUDENT
COURSE

STUDENT_COURSE
--------------
student_id
course_id

Example

@ManyToMany
@JoinTable(
name="student_course",
joinColumns=@JoinColumn(name="student_id"),
inverseJoinColumns=@JoinColumn(name="course_id")
)
private List<Course> courses;

Q6. What is mappedBy?

Answer

mappedBy tells Hibernate which side owns the relationship.

Only one side should maintain the foreign key.

Diagram

flowchart LR
Customer --> Order
Order -->|Owns FK| Customer

Example

@OneToMany(mappedBy = "customer")
private List<Order> orders;
@ManyToOne
@JoinColumn(name="customer_id")
private Customer customer;

Here,

Order owns the relationship.

Customer is the inverse side.


Q7. What is the Owning Side?

Answer

The owning side controls database updates.

The side containing @JoinColumn is always the owning side.

Example

@ManyToOne
@JoinColumn(name="customer_id")
Customer customer;

Hibernate updates the foreign key using this entity.

Rule

Always update the owning side.


Q8. What is CascadeType?

Answer

Cascade automatically propagates operations from parent to child.

Diagram

flowchart TD
Customer --> Save

Save --> Orders
Save --> Address

Example

@OneToMany(
cascade = CascadeType.ALL,
mappedBy = "customer")
private List<Order> orders;

Cascade Types

Type Meaning
PERSIST Save child
MERGE Update child
REMOVE Delete child
REFRESH Reload child
DETACH Detach child
ALL Everything

Q9. What is Orphan Removal?

Answer

Removing a child from a collection automatically deletes it.

Example

@OneToMany(
mappedBy="customer",
orphanRemoval=true
)
private List<Order> orders;

Example

customer.getOrders().remove(order);

Hibernate executes

DELETE FROM orders
WHERE id=?

Diagram

flowchart LR
Customer --> Order

Order --> Removed

Removed --> Delete

Difference

Cascade REMOVE

Deletes when parent is deleted.

Orphan Removal

Deletes when child is removed from collection.


Q10. What are the best practices for Entity Relationships?

Answer

Prefer LAZY Loading

@ManyToOne(fetch = FetchType.LAZY)

Avoid EAGER Collections

Bad

@OneToMany(fetch = FetchType.EAGER)

Can lead to N+1 queries and huge object graphs.


Keep Relationships Bidirectional Only When Needed

Unnecessary bidirectional relationships increase complexity.


Synchronize Both Sides

public void addOrder(Order order){

orders.add(order);

order.setCustomer(this);

}

Avoid ManyToMany in Enterprise Applications

Prefer an intermediate entity.

Instead of

Student
Course

Create

Student

Enrollment

Course

This allows storing

  • Enrollment Date
  • Grade
  • Status
  • Created By

Use DTOs in REST APIs

Never expose entities directly.

Controller

↓

DTO

↓

JSON

Banking Example

flowchart TD

Customer --> Account

Account --> Transaction

Customer --> Address

Customer --> Card

Common Interview Mistakes

❌ Using EAGER everywhere

❌ Forgetting mappedBy

❌ Updating inverse side only

❌ Using Cascade.ALL blindly

❌ Exposing Entities in REST

❌ Using ManyToMany for everything

❌ Ignoring orphanRemoval

❌ Infinite recursion during JSON serialization


Quick Revision

Annotation Purpose
@OneToOne One object owns another
@OneToMany Parent has multiple children
@ManyToOne Multiple children belong to one parent
@ManyToMany Many-to-many relationship
mappedBy Specifies inverse side
JoinColumn Foreign key column
JoinTable Intermediate table
Cascade Propagate operations
orphanRemoval Delete removed children
FetchType.LAZY Load on demand

Interview Tips

  • Prefer LAZY fetching for most associations.
  • Always understand the owning side of a relationship.
  • Use mappedBy correctly to avoid duplicate foreign keys.
  • Keep both sides of a bidirectional relationship synchronized.
  • Avoid exposing JPA entities directly in REST APIs.
  • Replace complex @ManyToMany mappings with an explicit join entity in production systems.
  • Be aware of the N+1 query problem and use JOIN FETCH or EntityGraph when appropriate.

Key Takeaways

  • JPA supports four relationship types: One-to-One, One-to-Many, Many-to-One, and Many-to-Many.
  • The owning side is responsible for updating the foreign key.
  • mappedBy identifies the inverse side in bidirectional relationships.
  • Use CascadeType only where lifecycle propagation is required.
  • orphanRemoval=true automatically deletes child entities removed from a parent collection.
  • Prefer LAZY loading to improve application performance.
  • Design relationships based on the domain model rather than the database schema.
  • Understanding entity relationships is essential for building scalable enterprise applications and performing well in Spring Boot, Hibernate, and JPA interviews.