Uploaded image for project: 'Spring Roo'
  1. Spring Roo
  2. ROO-2514

Controllers shouldn't call findAll on each request

    Details

    • Type: Improvement
    • Status: Resolved
    • Priority: Minor
    • Resolution: Complete
    • Affects Version/s: 1.2.0.RC1
    • Fix Version/s: 1.2.0.RELEASE
    • Component/s: WEB MVC
    • Labels:
      None

      Description

      As explained in the forum thread, and using the Pet entity as an example, the controller code generated by Roo calls findAllPets() upon every request, thanks to the presence of this method:

      PetController_Roo_Controller.aj
      @ModelAttribute("pets")
      public Collection<Pet> PetController.populatePets() {
          return Pet.findAllPets();
      }

      This is wasteful given that:

      • Some of the controller's request handling methods (e.g. "show" and "delete") don't even use the returned list of Pets.
      • The "list" method obtains its own list of Pets (usually via findPetEntries()).
      • The "create*" and "update*" methods only need the list of all Pets if the Pet class has a Pet (or Pets) field.

      We can make the scaffolded controllers more performant by only obtaining the list of all Pets when it's actually required.

      In the meantime, the workaround is as follows:

      1. Push in the populatePets method and have it return null (saves time in the "list" method)
      2. If the entity has a field of its own type (or a collection thereof), push in the "create*" and "update*" methods and modify them to explicitly put the "pets" list into the model, for example (showing the create* methods):
      PetController.java
      @RequestMapping(params = "form", method = RequestMethod.GET)
      public String createForm(Model uiModel) {
          uiModel.addAttribute("pets", Pet.findAllPets());
          uiModel.addAttribute("pet", new Pet());
          return "pets/create";
      }
      
      @RequestMapping(method = RequestMethod.POST)
      public String create(@Valid Pet pet, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
          if (bindingResult.hasErrors()) {
              uiModel.addAttribute("pets", Pet.findAllPets());
              uiModel.addAttribute("pet", pet);
              return "pets/create";
          }
          uiModel.asMap().clear();
          pet.persist();
          return "redirect:/pets/" + encodeUrlPathSegment(pet.getId().toString(), httpServletRequest);
      }

        Attachments

          Activity

            People

            • Assignee:
              aswan Andrew Swan
              Reporter:
              aswan Andrew Swan
            • Votes:
              14 Vote for this issue
              Watchers:
              10 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: