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);
}
}