Home > Blockchain >  Spring boot Jpa search data with multiple fields and paginate results
Spring boot Jpa search data with multiple fields and paginate results

Time:05-18

I am trying to search data on the basis of 5 input fields in spring boot jpa repository also in result will get multiple columns data in pagination. So suppose out of 5 fields only 4 input fields is given then it will search on the basis of 4 input data with and conditions. Can any one please provide complete code with explaination.

CodePudding user response:

I used Specification inside my projects so that I can create dynamic queries depending if parameter exists.

First, you need to create a util class where you keep your Specifications so that you can call them statically.

public class YourSpecifications {
    private YourSpecifications() {
        throw new IllegalStateException("Utility Class");
    }

    public static Specification<YourEntity> ifExistsEquals(ParameterType parameterNullable) {
        return (root, query, criteriaBuilder) -> Optional.ofNullable(parameterNullable)
                .map(parameter -> criteriaBuilder.equal(root.get("yourFieldForParameter"), parameter))
                .orElse(criteriaBuilder.conjunction()); // Thanks to this code block if your parameter does not exist it will not include inside query

    }
}

To execute our queries with specifications, we need to add another implementation which is JpaSpecificationExecutor<T> inside our Repository interface.

public interface YourRepository extends JpaRepository<YourEntity, Long>, JpaSpecificationExecutor<YourEntity> {// I defined my primary key as Long
}

Now we can create a filter inside our service layer

public class YourService {
    private static final String ORDER_BY = "id"; //your preference 
    private final YourRepository yourRepository;

    public Page<YourEntity> findAll(YourParameter yourParamNullable, Integer page, Integer size) {
        Specification<BasketEntity> filter =
                Specification.where(YourSpecifications.ifExistsEquals(yourParamNullable))// more queries with .and(), .or(). etc. 

        return yourRepository.findAll(filter, PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, ORDER_BY)));//Best to convert your own dto this is just an example
    }
}

CodePudding user response:

I created an article that describes exactly this. You can read it here: https://pavankjadda.medium.com/search-data-across-multiple-columns-using-spring-data-jpa-fc0a24799991

  • Related