Das Entity Warehouse erweitert JpaRepository<Entity, Id> und JpaSpecificationExecutor<Entity>, und EntitySpec erweitert Specification<Entity>
P粉653045807
P粉653045807 2024-04-06 17:11:03
0
1
416

Dies ist mein Endpunkt http://localhost:8080/country/all Sie können allen Ländern antworten

Retouren wurden nicht gefunden, wenn ich sie filtern möchte Land ist leer und gibt eine Ausnahme zurück throw new RecordNotFoundException("Ungültige Anfrage, keine Daten zurückgegeben"); Es gibt einen Eintrag in meiner Datenbank County_Code Land KM Komoren

Das ist meine JSON-Nutzlast

{
     "country_code":["KM"]
    }
public interface CountryRepo extends JpaRepository<Country, Id>, JpaSpecificationExecutor<Country> {

    }
    public final class CountrySpecs<T> implements Specification<T> {
    
    final private SearchCriteria criteria;
    
    public CountrySpecs(SearchCriteria searchCriteria) {
        this.criteria = searchCriteria;
    }

        @Override
        @Nullable
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        switch (criteria.getOperation()) {
            case ":":
              if (root.get(criteria.getKey()).getJavaType() == String.class) {
                return builder.like(
                        root.<String>get(criteria.getKey()),
                        "%" + criteria.getValue() + "%");
              } else {
                return builder.equal(root.get(criteria.getKey()),
                        criteria.getValue());
              }
            case "=":
              return builder.equal(root.get(criteria.getKey()),
                      criteria.getValue());
            case "in":
              return builder.in(root.get(criteria.getKey())).value(criteria.getValue());
            default:
              return null;
       }
       }
    }
     @GetMapping("/all")
     public ResponseEntity<Map<String, Object>> getAll(
         @Valid @RequestBody Map<String, Object> request) throws Exception {
         List<Country> countries = new ArrayList<>();
 
         int page = (request.get("page") != null) ? (int) request.get("page") : 1;
         int size = (request.get("size") != null) ? (int) request.get("size") : DEFAULT_SIZE;

        // page-1 mi da la possibilità di scrivere nel payload page=1
        Pageable pageable = PageRequest.of(
           page,
          size);
        Page<Country> pageCountries = null;

       /* Validazione */

       /* filter */
       if (request.keySet().size() > 0) {
          CountrySpecs<Country> countrySpecs = null;
          if (request.keySet().contains("country_code")) {
             List<String> list = (List<String>) request.get("country_code");
             /* paginazione filtrata */
             countrySpecs = new CountrySpecs<>(new SearchCriteria("country_code", "in", list));
             pageCountries = repository.findAll(
               countrySpecs,
               pageable);
             countries = pageCountries.getContent();
          }
      } else {
        pageCountries = repository.findAll(pageable);
        countries = pageCountries.getContent();
      }

      if (countries.isEmpty()) {
        // la tabella interrogata non ha dati
        throw new RecordNotFoundException("无效请求,无数据返回");
      }

      Map<String, Object> obj = new TreeMap<>();
      // aggiunta delle informazioni sulla paginazione
      obj.put("countries", countries);
      obj.put("currentPage", pageCountries.getNumber());
      obj.put("totalItems", pageCountries.getTotalElements());
      obj.put("totalPages", pageCountries.getTotalPages());

     ResponseEntity<Map<String, Object>> response = new ResponseEntity<>(
        obj,
        HttpStatus.OK);
       return response;
    }

Danke Rashin, ich habe den Code verbessert, aber das Problem besteht immer noch! Ich hoffe, dass eine Lösung gefunden werden kann.

Nach dem Zurücksetzen des Codes funktioniert es...

P粉653045807
P粉653045807

Antworte allen(1)
P粉198814372
enter code here

 
 @GetMapping("/all")
  public ResponseEntity> getAll(
      @Valid @RequestBody Map request) {

try {
  countryService.customPage.init();
  
  if (request.keySet().contains("page")) {
    countryService.customPage.setPage(request.get("page").toString());
  }

  if (request.keySet().contains("size")) {
    countryService.customPage.setSize(request.get("size").toString());
  }

  
  Sort ordine=(request.keySet().contains("sort")) ? 
      countryService.customSort.sorted((CustomSort[]) request.get("sort"))
      : Sort.unsorted();
  
  // page default value 1 and size default value DEFAULT_SIZE
  Pageable pageable = PageRequest.of(
      countryService.customPage.getPage(),
      countryService.customPage.getSize(),
      ordine
      );
      

  /* Validazione */

  Map countries;
  /* filter */
  if (request.keySet().contains("country_code")) {
    List list = (List) request.get("country_code");
    countries = countryService.getByCountryCode(list, pageable);
  } else {
    countries = countryService.getAll(pageable);
  }

  //countryService restituisce empty se la pagina richiesta è maggiore di quelle presenti
  //se la richiesta non restituisce risultati
  if (countryService.isEmpty()) {
    
    if (((Integer) countries.get("currentPage")).intValue()>
        ((Integer) countries.get("totalPages")).intValue()) {
      throw new RecordNotFoundException("The page " +
      (countryService.customPage.getPage()+1) +
      " is over the total page");
    }
    // la tabella interrogata non ha dati
    throw new RecordNotFoundException("Invalid request, return no data");
  }

  ResponseEntity> response = new ResponseEntity(
      countries,
      HttpStatus.OK);
  return response;
} catch (RecordNotFoundException | NumberFormatException re) {
  Map errors = new LinkedHashMap();
  errors.put("errors", re.getMessage());
  ResponseEntity> response = new ResponseEntity(
      errors,
      HttpStatus.INTERNAL_SERVER_ERROR);
  return response;
} catch (Exception e) {
  Map errors = new LinkedHashMap();
  errors.put("errors", Errors.all);
  ResponseEntity> response = new ResponseEntity(
      errors,
      HttpStatus.BAD_REQUEST);
  return response;
}
}


 /**
 * @param list
 * @param pageable
 * @return
 */
public Map getByCountryCode(List list, Pageable pageable) {
    /* paginazione filtrata */
    Specs countrySpecs = new Specs(new SearchCriteria("country_code", "in", list));
    pageCountries = repository.findAll(
        countrySpecs,
        pageable);
    countries = pageCountries.getContent();

    Map service = new LinkedHashMap();
    // aggiunta delle informazioni sulla paginazione
    service.put("countries", countries);
    service.put("currentPage", pageCountries.getNumber()+1);
    service.put("totalItems", pageCountries.getTotalElements());
    service.put("totalForPage", pageCountries.getSize());
    service.put("totalPages", pageCountries.getTotalPages());

    return service;
}
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!