Many-to-One Relationship |
Explanation of Many-to-One Relationship in Spring Boot
In a many-to-one relationship, multiple entities from one table (child) are related to a single entity in another table (parent). This is common in real-world scenarios, like multiple employees belonging to a single department.
Example: Employees and Departments in Spring Boot
Here’s how you can implement a many-to-one relationship in Spring Boot:
Step 1: Define the Entity Classes
-
Department Entity:
@Entity public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // Getters and Setters }
-
Employee Entity:
@Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne @JoinColumn(name = "department_id") private Department department; // Getters and Setters }
Step 2: Create Repositories
- Define repositories for both entities:
public interface EmployeeRepository extends JpaRepository<Employee, Long> {} public interface DepartmentRepository extends JpaRepository<Department, Long> {}
Step 3: Save Data
- Save departments and assign them to employees.
@RestController @RequestMapping("/api") public class EmployeeController { @Autowired private EmployeeRepository employeeRepository; @Autowired private DepartmentRepository departmentRepository; @PostMapping("/addEmployee") public Employee addEmployee(@RequestBody Employee employee) { return employeeRepository.save(employee); } @PostMapping("/addDepartment") public Department addDepartment(@RequestBody Department department) { return departmentRepository.save(department); } }
Step 4: Test the Relationship
- Save a few departments, e.g., "IT" and "HR."
- Create employees and associate them with their respective departments by setting the
department
field.
Key Benefits of Many-to-One Relationships in Spring Boot
- Streamlined database design with reduced redundancy.
- Easy navigation of relationships (e.g., fetch all employees of a department).
- Simplified data management using JPA's cascading operations.
This approach ensures scalability and clarity, especially for applications with complex data relationships!
No comments:
Post a Comment