This exercise guides you through implementing a bidirectional @OneToMany relationship between the Department and Staff entities in a Spring Boot application.
The tutorial covers the following core development tasks:
Creating the Department Entity: You create a new Department class with fields for deptId, deptName, address, and phone.
Bidirectional Mapping: * In the Department class, you use the @OneToMany annotation with mappedBy = "department" to establish that one department can have many staff members.
In the Staff class, you use the @ManyToOne and @JoinColumn(name = "dept_id") annotations to create a foreign key column in the staff table that links back to the department.
Boilerplate Code: You must generate getters, setters, and toString methods for both entities to ensure proper data handling.
DepartmentRepository: You create a new interface extending JpaRepository to handle database operations for the Department entity.
Database Seeding: The data.sql file is updated to insert initial department records and use UPDATE statements to assign existing staff members to their respective departments.
H2 Verification: After running the application, you verify the relationship in the H2 database console, confirming that the STAFF table now includes a DEPT_ID join column.
Controller Updates: The StaffController is modified to inject the DepartmentRepository. The showSignUpForm and showUpdateForm methods are updated to fetch all departments and add them to the model, allowing users to select a department from a list.
UI Updates (Thymeleaf):
List View: You update list-staff.html to display the Department ID and Department Name for each staff member using the safe navigation operator (staff.department?.deptName).
Forms: The add-staff.html and update-staff.html files are updated to include a dropdown <select> menu populated with department options.
The final steps involve re-running the staffApplication to test the new functionality:
Adding a new staff member and selecting their department from the dropdown menu.
Updating existing staff details, such as salary, and confirming the changes are correctly reflected in the updated list view.