Hackforge Academy

Category: spring_boot

One-to-Many

Published on 26 Jun 2026

Explanation

A One-to-Many relationship exists when one parent entity can have multiple child entities. For example, one Department can have many Employees. In JPA, this relationship is represented using the @OneToMany and @ManyToOne annotations.

Code:

@Entity
public class Department {

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

    private String name;
}

Explanation

The child entity contains a @ManyToOne relationship pointing to the parent entity. This creates a foreign key column in the child table.

Code:

@Entity
public class Employee {

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

    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
}

Explanation

The parent entity uses the @OneToMany annotation to maintain a collection of child entities. The mappedBy attribute indicates that the relationship is managed by the child entity.

Code:

@Entity
public class Department {

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

    private String name;

    @OneToMany(mappedBy = "department")
    private List<Employee> employees;
}

Explanation

Create repository interfaces for both entities. Spring Data JPA automatically provides CRUD operations without requiring manual SQL queries.

Code:

public interface DepartmentRepository 
extends JpaRepository<Department, Long> {
}

public interface EmployeeRepository 
extends JpaRepository<Employee, Long> {
}

Explanation

A REST API can return a department along with its employees. When the department is fetched, the associated employee list is included in the JSON response.

Code:

@RestController
@RequestMapping("/departments")
public class DepartmentController {

    @Autowired
    private 
DepartmentRepository departmentRepository;

    @GetMapping("/{id}")
    public Department 
getDepartment(@PathVariable Long id) {
        return 
departmentRepository.findById(id).
orElse(null);
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community