Search code examples
javahibernatebrowser-cacheehcache

Load data in cache with java


I´m a little lost with a problem. I need to save in cache a list of data which I query from the Database. The list is very big and when it loads in a combobox isn´t optim. Any ideas about this?

My code is:

  • Controller:

    model.addAttribute(LISTA_LUGARES,lugarService.findLugaresByIdMunicipio(documentacionDTO.getIdMunicipio()));
    
  • Service:

    public List<Lugar> findLugaresByIdMunicipio(Long idMunicipio) {
        return this.lugarRepository.findLugaresByIdMunicipio(idMunicipio);
    }
    
  • Repository:

    @Query("from Lugar l where l.municipio.id = :idMunicipio order by l.nombre asc")
    List<Lugar> findLugaresByIdMunicipio(@Param("idMunicipio") Long idMunicipio);
    
  • HTML:

     <select
        id="lugar" th:field="*{idLugar}" class="form-control">
        <option th:each="type : ${lugar}" th:value="${type.id}"
        th:text="#{${type.nombre}}">opciones</option>
        </select>
    

Solution

  • You can use something like EhCache to set the query as @Cacheable, this will indicate that the result of invoking a method (or all methods in a class) can be cached.

    Each time an advised method is invoked, the caching behavior will be applied, checking whether the method was already invoked for the given arguments:

    Here's an example