Many-to-One Mapping in Spring Data JPA with Complete Example

Many-to-One Mapping is one of the most commonly used relationship types in enterprise applications. It allows multiple records from one table to be associated with a single record from another table.


Understanding Many-to-One Mapping is essential because it appears frequently in Spring Boot projects and technical interviews.


What is Many-to-One Mapping?

A Many-to-One relationship means many child entities can be associated with a single parent entity.


Employee
     |
Employee
     |
Employee
     |
     v
Department

Many employees can belong to one department.


Real World Examples

  • Employees → Department
  • Orders → Customer
  • Books → Author
  • Students → University
  • Accounts → Branch

Database Structure

department


id

name

employee


id

name

salary

department_id

department_id acts as the foreign key.


Create Department Entity


@Entity
@Table(name = "department")
public class Department {

    @Id
    @GeneratedValue(
        strategy =
        GenerationType.IDENTITY
    )
    private Long id;

    private String name;

}

Create Employee Entity


@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(
        strategy =
        GenerationType.IDENTITY
    )
    private Long id;

    private String name;

    private Double salary;

}

Adding @ManyToOne Relationship

The Employee entity references Department.



@ManyToOne

@JoinColumn(
    name = "department_id"
)

private Department department;

Understanding @ManyToOne

@ManyToOne tells JPA that many Employee records can belong to a single Department.



@ManyToOne

This is the most common relationship type in business applications.


Understanding @JoinColumn

@JoinColumn defines the foreign key column.



@JoinColumn(
    name = "department_id"
)

Hibernate creates and maintains this foreign key automatically.


Complete Employee Entity


@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(
        strategy =
        GenerationType.IDENTITY
    )
    private Long id;

    private String name;

    private Double salary;

    @ManyToOne

    @JoinColumn(
        name = "department_id"
    )

    private Department department;

}

Saving Data

Create Department


Department department =
    new Department();

department.setName(
    "Information Technology"
);

Create Employees


Employee employee1 =
    new Employee();

employee1.setName(
    "John"
);

employee1.setSalary(
    50000.0
);

employee1.setDepartment(
    department
);


Employee employee2 =
    new Employee();

employee2.setName(
    "David"
);

employee2.setSalary(
    70000.0
);

employee2.setDepartment(
    department
);

Both employees now belong to the same department.


Cascade Operations

Cascade operations automatically propagate persistence operations.



@ManyToOne(
    cascade =
    CascadeType.PERSIST
)

The Department can be automatically persisted when Employee is saved.


Repository Layer

Department Repository


@Repository
public interface DepartmentRepository
extends JpaRepository<
        Department,
        Long> {

}

Employee Repository


@Repository
public interface EmployeeRepository
extends JpaRepository<
        Employee,
        Long> {

}

Fetch Types

Eager Fetch


@ManyToOne(
    fetch =
    FetchType.EAGER
)

Department is loaded immediately.


Lazy Fetch


@ManyToOne(
    fetch =
    FetchType.LAZY
)

Department is loaded only when accessed.


Generated SQL Conceptually


SELECT *
FROM employee
WHERE department_id = 1

JPA automatically manages these relationships behind the scenes.


Many-to-One vs One-to-Many

Many-to-One One-to-Many
Employee → Department Department → Employees
Child Perspective Parent Perspective
Contains Foreign Key References Collection

Relationship Ownership

The Employee entity owns the relationship because it contains the foreign key column.


This is another popular Spring interview question.


Common Interview Questions

What is Many-to-One Mapping?

A relationship where multiple child entities reference a single parent entity.


Which side owns the relationship?

The side containing the foreign key owns the relationship.


What does @JoinColumn do?

It defines the column used as the foreign key.


What is the default fetch type?

EAGER for Many-to-One relationships.


Can many employees belong to one department?

Yes. That is the primary purpose of Many-to-One Mapping.


Best Practices

  • Understand ownership of relationships.
  • Prefer LAZY loading when appropriate.
  • Use Cascade carefully.
  • Avoid unnecessary fetching.
  • Use DTOs in REST APIs.

Frequently Asked Questions (FAQ)

Can an employee exist without a department?

Yes, depending on business rules and database constraints.


Can multiple employees share the same department?

Yes. This is the primary use case of a Many-to-One relationship.


Does Hibernate create the foreign key automatically?

Yes. Hibernate creates and manages foreign keys when configured correctly.


Conclusion

Many-to-One Mapping is one of the most fundamental relationship types in Spring Data JPA. Understanding @ManyToOne, @JoinColumn, ownership rules, Cascade Types and Fetch Strategies is essential for building enterprise applications and succeeding in Spring Boot interviews.


Keywords

ManyToOne Mapping JPA, @ManyToOne Example, Spring Data JPA Relationships, Hibernate Many To One, JPA Relationship Mapping, Spring Boot JPA Tutorial, Foreign Key Mapping, JPA Interview Questions, Database Relationships, Entity Relationships, Spring Data JPA Tutorial, Java Backend Development, Hibernate Mapping, Spring Boot Database Design, @ManyToOne Annotation

Many-to-One Mapping in Spring Data JPA with Complete Example Many-to-One Mapping in Spring Data JPA with Complete Example Reviewed by 13thGhost on 10:30 AM Rating: 5

Recommended Posts

Powered by Blogger.