So i have grades controller, and i want to display table that will show students first name, students last name and then grades from table grades. I linked grades by grades_id in students so that every student has their own grades.
Problem is, i cant figure out how to make it work.
@GetMapping("/grades")
public String grades(Model theModel){
List<students> theStudents = studentService.findAll();
List<grades> theGrades = null;
for(students s : theStudents){
theGrades = (List<grades>) gradesService.findById(s.getGrades_id());
}
theModel.addAttribute("grades",theGrades);
theModel.addAttribute("students",theStudents);
return "/ediary/principal/grades";
}
/
public grades findById(int theId) {
Optional<grades> result = gradesRepository.findById(theId);
grades theGrades = null;
if(result.isPresent()){
theGrades = result.get();
} else{
throw new RuntimeException("Did not find grade id - " theId);
}
return theGrades;
}
I tried something like this, but its obviously not working,
so the main thing im trying is this:
| first name | last name | English | Math | ...
How do i do this?
CodePudding user response:
Instead of returning Optional
from findById()
return List
and instead of findById()
write findAllById()
inside the findById().
for example
List<grades> result = gradesRepository.findAllById(theId);
CodePudding user response:
I think you might reconsider your conception , you can achieve that easily if you did Student have a list of grades and the Grade entity is the owner of the relationship in terms of holding the primary key of the Student entity as a foreign key , and then when you fetch the Student you can get every Grade object associated with it.