One-to-Many and Many-to-One Mapping

A one-to-many relationship means one parent record owns many child records, such as one Department with many Students. Seen from the child, the same link is many-to-one. In the database, the child table holds the foreign key (department_id in students) pointing to the parent. In JPA, the parent declares @OneToMany (a list of children) and the child declares @ManyToOne with @JoinColumn, and the child side owns the foreign key. It is used wherever data forms a hierarchy (department and students, order and items, blog post and comments), so you can work with a parent and its children as objects.

Features

  • Cascade: saving or deleting the parent also saves or deletes its children.
  • Orphan removal: a child removed from the parent’s list is deleted from the database.
  • Children can be added, removed, or moved to another parent.
  • Parents can be found by a property of their children.
  • Children load only when needed (lazy), or together with the parent in one query (JOIN FETCH).

Hands-on Experiment: Creating a spring boot application with One-to-Many and Many-to-One Mapping

The following steps are involved in developing this hands-on experiment.

Step 1: Generate the Project

Step 2: Project Structure

Step 3: pom.xml

Step 4: application.yml

Step 5: Create Entity Class

Step 6: Create Repository Interface

Step 7: Create Service Class

Step 8: Create Controller Class

Step 9: Main Application Class

Step 10: Run the Main Application Class

Step 1: Configure the Project on Spring Initializr

Go to start.spring.io and set:

  • Project: Maven
  • Language: Java
  • Spring Boot version: 3.2.x
  • Group: com.example
  • Artifact: parentchild
  • Name: parentchild
  • Package name: com.example.parentchild
  • Packaging: Jar
  • Java: 17
  • Dependencies: Spring Web, Spring Data JPA, PostgreSQL Driver

Click Generate to download the ZIP, then extract and import it into your IDE as a Maven project.

Step 2: Generated Project Structure

Step 3: Explore pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.5</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>department-student-parentchild-demo</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Step 4: application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/student_parentchild_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    username: root
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

server:
  port: 8082

Step 5: Create Entity Class

package com.example.parentchild.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;

import java.util.ArrayList;
import java.util.List;

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

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

    @Column(nullable = false, unique = true, length = 100)
    private String name;

    // ONE department has MANY students.
    // mappedBy = "department" -> the foreign key lives in the students table, owned by Student.department
    // cascade = ALL           -> saving or deleting a department also saves or deletes its students
    // orphanRemoval = true    -> a student removed from this list is deleted from the database
    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnoreProperties("department")      // stops the endless loop department -> students -> department ...
    private List<Student> students = new ArrayList<>();

    public Department() {}

    public Department(String name) {
        this.name = name;
    }

    // Keeps BOTH sides of the relationship in sync
    public void addStudent(Student student) {
        students.add(student);
        student.setDepartment(this);
    }

    public void removeStudent(Student student) {
        students.remove(student);
        student.setDepartment(null);
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public List<Student> getStudents() { return students; }

    // Used when a department is created from JSON that contains a "students" array
    public void setStudents(List<Student> newStudents) {
        this.students.clear();
        if (newStudents != null) {
            newStudents.forEach(this::addStudent);
        }
    }
}
package com.example.parentchild.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {

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

    @Column(nullable = false, length = 100)
    private String name;

    @Column(nullable = false, unique = true, length = 150)
    private String email;

    // MANY students belong to ONE department.
    // This is the OWNING side: it creates the foreign key column department_id in the students table.
    @ManyToOne
    @JoinColumn(name = "department_id")
    @JsonIgnoreProperties("students")        // show the department's id and name only, not its whole student list
    private Department department;

    public Student() {}

    public Student(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public Department getDepartment() { return department; }
    public void setDepartment(Department department) { this.department = department; }
}

Step 6: Create below Repository Interface

package com.example.parentchild.repository;

import com.example.parentchild.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface DepartmentRepository extends JpaRepository<Department, Long> {

    boolean existsByNameIgnoreCase(String name);

    // Loads every parent AND its children in ONE query (JOIN FETCH)
    @Query("SELECT DISTINCT d FROM Department d LEFT JOIN FETCH d.students ORDER BY d.name")
    List<Department> findAllWithStudents();

    // Finds PARENTS by a property of their CHILDREN: department.students.name
    List<Department> findDistinctByStudentsNameContainingIgnoreCase(String name);
}
package com.example.parentchild.repository;

import com.example.parentchild.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

    boolean existsByEmail(String email);

    // Walks the relationship: student.department.id = ?
    List<Student> findByDepartmentId(Long departmentId);

    long countByDepartmentId(Long departmentId);
}

Step 7: Create below Service class

package com.example.parentchild.service;

import com.example.parentchild.entity.Department;
import com.example.parentchild.entity.Student;
import com.example.parentchild.repository.DepartmentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class DepartmentService {

    private final DepartmentRepository repository;

    public DepartmentService(DepartmentRepository repository) {
        this.repository = repository;
    }

    // Saving a parent also saves its children (cascade)
    public Optional<Department> create(Department department) {
        if (repository.existsByNameIgnoreCase(department.getName())) {
            return Optional.empty();
        }
        department.setId(null);
        return Optional.of(repository.save(department));
    }

    // 1 query: parents and children together
    public List<Department> findAllWithStudents() {
        return repository.findAllWithStudents();
    }

    // 1 query for parents, then 1 more query PER parent when the children are read (N+1)
    public List<Department> findAllLazy() {
        return repository.findAll();
    }

    public Optional<Department> findById(Long id) {
        return repository.findById(id);
    }

    public List<Department> findByStudentName(String name) {
        return repository.findDistinctByStudentsNameContainingIgnoreCase(name);
    }

    public Optional<Department> rename(Long id, String newName) {
        return repository.findById(id).map(department -> {
            department.setName(newName);
            return repository.save(department);
        });
    }

    // Removes ONE child from the parent's list; orphanRemoval deletes that student row
    @Transactional
    public boolean removeStudent(Long departmentId, Long studentId) {
        Optional<Department> department = repository.findById(departmentId);
        if (department.isEmpty()) {
            return false;
        }
        Optional<Student> child = department.get().getStudents().stream()
                .filter(s -> s.getId().equals(studentId))
                .findFirst();
        if (child.isEmpty()) {
            return false;
        }
        department.get().removeStudent(child.get());
        return true;
    }

    // Deleting the parent also deletes all its children (cascade)
    public boolean delete(Long id) {
        if (!repository.existsById(id)) {
            return false;
        }
        repository.deleteById(id);
        return true;
    }
}
package com.example.parentchild.service;

import com.example.parentchild.entity.Department;
import com.example.parentchild.entity.Student;
import com.example.parentchild.repository.DepartmentRepository;
import com.example.parentchild.repository.StudentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

    private final StudentRepository studentRepository;
    private final DepartmentRepository departmentRepository;

    public StudentService(StudentRepository studentRepository, DepartmentRepository departmentRepository) {
        this.studentRepository = studentRepository;
        this.departmentRepository = departmentRepository;
    }

    public boolean emailExists(String email) {
        return studentRepository.existsByEmail(email);
    }

    // Adds a new child to an existing parent. Empty result = department not found.
    @Transactional
    public Optional<Student> addToDepartment(Long departmentId, Student student) {
        return departmentRepository.findById(departmentId).map(department -> {
            student.setId(null);
            student.setDepartment(department);          // sets the foreign key department_id
            return studentRepository.save(student);
        });
    }

    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    public Optional<Student> findById(Long id) {
        return studentRepository.findById(id);
    }

    public List<Student> findByDepartment(Long departmentId) {
        return studentRepository.findByDepartmentId(departmentId);
    }

    public long countByDepartment(Long departmentId) {
        return studentRepository.countByDepartmentId(departmentId);
    }

    // Moves a child to another parent by changing the foreign key
    @Transactional
    public Optional<Student> moveToDepartment(Long studentId, Long departmentId) {
        Optional<Student> student = studentRepository.findById(studentId);
        Optional<Department> department = departmentRepository.findById(departmentId);
        if (student.isEmpty() || department.isEmpty()) {
            return Optional.empty();
        }
        student.get().setDepartment(department.get());
        return student;
    }

    public boolean delete(Long id) {
        if (!studentRepository.existsById(id)) {
            return false;
        }
        studentRepository.deleteById(id);
        return true;
    }
}

Step 8: Create Controller class

package com.example.parentchild.controller;

import com.example.parentchild.entity.Department;
import com.example.parentchild.entity.Student;
import com.example.parentchild.service.DepartmentService;
import com.example.parentchild.service.StudentService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

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

    private final DepartmentService departmentService;
    private final StudentService studentService;

    public DepartmentController(DepartmentService departmentService, StudentService studentService) {
        this.departmentService = departmentService;
        this.studentService = studentService;
    }

    // ---------- PARENT ----------
    // The body may contain a "students" array: they are saved together with the department
    @PostMapping
    public ResponseEntity<Object> create(@RequestBody Department department) {
        return departmentService.create(department)
                .<ResponseEntity<Object>>map(saved -> ResponseEntity.status(HttpStatus.CREATED).body(saved))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.CONFLICT)
                        .body(Map.of("error", "Department already exists")));
    }

    // Efficient: parents and children in ONE query (JOIN FETCH)
    @GetMapping
    public List<Department> getAll() {
        return departmentService.findAllWithStudents();
    }

    // Same output, but 1 + N queries (compare the console!)
    @GetMapping("/lazy")
    public List<Department> getAllLazy() {
        return departmentService.findAllLazy();
    }

    // Find parents by a property of their children
    @GetMapping("/by-student")
    public List<Department> byStudent(@RequestParam String name) {
        return departmentService.findByStudentName(name);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Department> getById(@PathVariable Long id) {
        return departmentService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Department> rename(@PathVariable Long id, @RequestBody Department department) {
        return departmentService.rename(id, department.getName())
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // Also deletes all the department's students (cascade)
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        return departmentService.delete(id) ? ResponseEntity.noContent().build()
                                            : ResponseEntity.notFound().build();
    }

    // ---------- CHILDREN of a parent ----------
    @GetMapping("/{id}/students")
    public ResponseEntity<List<Student>> students(@PathVariable Long id) {
        if (departmentService.findById(id).isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(studentService.findByDepartment(id));
    }

    @GetMapping("/{id}/students/count")
    public ResponseEntity<Map<String, Long>> studentCount(@PathVariable Long id) {
        if (departmentService.findById(id).isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(Map.of("count", studentService.countByDepartment(id)));
    }

    @PostMapping("/{id}/students")
    public ResponseEntity<Object> addStudent(@PathVariable Long id, @RequestBody Student student) {
        if (studentService.emailExists(student.getEmail())) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", "Email already exists"));
        }
        return studentService.addToDepartment(id, student)
                .<ResponseEntity<Object>>map(saved -> ResponseEntity.status(HttpStatus.CREATED).body(saved))
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // Removes ONE child from the parent (orphanRemoval deletes the student row)
    @DeleteMapping("/{id}/students/{studentId}")
    public ResponseEntity<Void> removeStudent(@PathVariable Long id, @PathVariable Long studentId) {
        return departmentService.removeStudent(id, studentId) ? ResponseEntity.noContent().build()
                                                              : ResponseEntity.notFound().build();
    }
}
package com.example.parentchild.controller;

import com.example.parentchild.entity.Student;
import com.example.parentchild.service.StudentService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/students")
public class StudentController {

    private final StudentService service;

    public StudentController(StudentService service) {
        this.service = service;
    }

    @GetMapping
    public List<Student> getAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Student> getById(@PathVariable Long id) {
        return service.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // Move a student to another department
    @PutMapping("/{id}/department/{departmentId}")
    public ResponseEntity<Student> move(@PathVariable Long id, @PathVariable Long departmentId) {
        return service.moveToDepartment(id, departmentId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        return service.delete(id) ? ResponseEntity.noContent().build()
                                  : ResponseEntity.notFound().build();
    }
}

Step 9: Main Application

package com.example.parentchild;

import com.example.parentchild.entity.Department;
import com.example.parentchild.entity.Student;
import com.example.parentchild.repository.DepartmentRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.List;

@SpringBootApplication
public class ParentChildApplication {

    public static void main(String[] args) {
        SpringApplication.run(ParentChildApplication.class, args);
    }

    // Adds sample data once. Saving a Department also saves its students (cascade).
    @Bean
    CommandLineRunner seedData(DepartmentRepository departmentRepository) {
        return args -> {
            if (departmentRepository.count() == 0) {
                Department cse = new Department("CSE");
                cse.addStudent(new Student("Ravi Kumar", "ravi@example.com"));
                cse.addStudent(new Student("Anil Verma", "anil@example.com"));

                Department ece = new Department("ECE");
                ece.addStudent(new Student("Sneha Reddy", "sneha@example.com"));
                ece.addStudent(new Student("Ravi Teja", "teja@example.com"));

                Department it = new Department("IT");
                it.addStudent(new Student("Priya Nair", "priya@example.com"));

                departmentRepository.saveAll(List.of(cse, ece, it));
            }
        };
    }
}

Step 10: Run the ParentChildApplication

Scroll to Top