Update OwnerController.java

This commit is contained in:
Yasaswini Desu 2025-02-21 12:25:12 +05:30 committed by GitHub
parent b1ad8a32fe
commit 9f20e90a0c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -80,8 +80,7 @@ class OwnerController {
} }
@GetMapping("/owners") @GetMapping("/owners")
public String processFindForm(@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result, public String processFindForm(@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result, Model model) {
Model model) {
// allow parameterless GET request for /owners to return all records // allow parameterless GET request for /owners to return all records
if (owner.getLastName() == null) { if (owner.getLastName() == null) {
owner.setLastName(""); // empty string signifies broadest possible search owner.setLastName(""); // empty string signifies broadest possible search
@ -152,4 +151,49 @@ class OwnerController {
return mav; return mav;
} }
// New method to delete an owner by ID
@PostMapping("/owners/{ownerId}/delete")
public String processDeleteOwner(@PathVariable("ownerId") int ownerId, RedirectAttributes redirectAttributes) {
this.owners.deleteById(ownerId);
redirectAttributes.addFlashAttribute("message", "Owner Deleted Successfully");
return "redirect:/owners";
}
// New method to search owners by first name
@GetMapping("/owners/findByFirstName")
public String processFindByFirstNameForm(@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result, Model model) {
// Allow parameterless GET request for /owners/findByFirstName to return all records
if (owner.getFirstName() == null) {
owner.setFirstName(""); // empty string signifies broadest possible search
}
// Use existing method to find owners by first name
Page<Owner> ownersResults = findPaginatedForOwnersFirstName(page, owner.getFirstName());
if (ownersResults.isEmpty()) {
// No owners found
result.rejectValue("firstName", "notFound", "not found");
return "owners/findOwners";
}
if (ownersResults.getTotalElements() == 1) {
// 1 owner found
owner = ownersResults.iterator().next();
return "redirect:/owners/" + owner.getId();
}
// Multiple owners found
return addPaginationModel(page, model, ownersResults);
}
// Helper method to paginate results for searching by first name
private Page<Owner> findPaginatedForOwnersFirstName(int page, String firstName) {
Pageable pageable = PageRequest.of(page - 1, 5); // Example page size of 5
return this.owners.findByFirstNameContaining(firstName, pageable); // Ensure this method exists in your repository
}
// Existing method to paginate owners by last name
private Page<Owner> findPaginatedForOwnersLastName(int page, String lastName) {
Pageable pageable = PageRequest.of(page - 1, 5); // Example page size of 5
return this.owners.findByLastNameContaining(lastName, pageable); // Ensure this method exists in your repository
}
} }