Search code examples
javaspring-bootspring-data-jpa

How to do filtering and pagination by two parameters in java using Specification


How to do filtering and pagination by two parameters in java using Specification, and pagination at the same time.

@Override
public Page<LocationsDetailsDTO> getAllAtmOrBranchesFilteredByCityNameAndBankType(String cityName, BankType bankType, int pageSize, int page) {
    Specification<LocationsDetails> specification = Specifications.where(LocationsDetailsSpecifications.hasCityName(cityName))
        .and(LocationsDetailsSpecifications.hasBankType(bankType));

    Pageable pageable = PageRequest.of(page, pageSize);
    return locationsRepository.findAll(specification, pageable)
        .map(this::convertToDTO);
}

public static Specification<LocationsDetails> hasCityName(String cityName) {
        return (r, q, cb) -> cityName == null ? null : cb.like(r.get("cityName"), (cityName));
    }

public static Specification<LocationsDetails> hasBankType(BankType bankType) {
        return (r, q, cb) -> bankType == null ? null : cb.equal(r.get("bankType"), bankType);
    }

This option does not work, the problem is in the findAll method

Error indication. My option does not work


Solution

  • Ensure that the provided cityName and bankType parameters have valid values and are not null. If they can be null, you should handle those cases in the specifications to avoid any errors or Check if the LocationsDetailsDTO class and the convertToDTO method are implemented correctly. Make sure that the method properly converts an instance of LocationsDetails to LocationsDetailsDTO.