0

I want to make multi fields filter with JpaRepository, but I need to keep pagination(Page).

I tried the following:

Page<Group> getAllByOrganizationAndIdNotInAndLocation_Id(Organization organization, Collection<Long> id, Long location_id, Pageable pageable);

However, in some cases, I do not receive all the expect variables and the query does not work as I intended

Lars Nielsen
  • 2,005
  • 2
  • 25
  • 48
  • 1
    Can you please clarify what "In some cases I can receive not all needed variables and this query don't work as I needed." means? – Jens Schauder Mar 19 '21 at 08:03
  • You write you tried something like, is it what you tried or is it not? Can you submit a minimal working example? – Lars Nielsen Mar 19 '21 at 08:42

2 Answers2

1

When variables are optional you need to handle their absence. You need to dynamically create your query. In Spring Data JPA you have three options:

  • Criteria API
  • QueryDSL
  • Query By Example

You can read more on that here: Dynamic spring data jpa repository query with arbitrary AND clauses

Robert Niestroj
  • 15,299
  • 14
  • 76
  • 119
1

You may just use this library in combination with Spring's Pageable: https://github.com/turkraft/spring-filter

It will let you run search queries such as:

/search?filter= average(ratings) > 4.5 and brand.name in ('audi', 'land rover') and (year > 2018 or km < 50000) and color : 'white' and accidents is empty

Spring's Pageable will let you paginate with &page=34&size=20

torshid
  • 137
  • 1
  • 9