0

I have this spring JPA query:

Optional<List<Result>> findAllByAvailabilityAndItemCategoryAndIdLessThanOrderByIdDesc(
            String availability, String category, long cursor, Pageable pageable
    );

When passing a null value as one of the parameters, JPA looks for the actual null value in the database. Example:

repository.findAllByAvailabilityAndItemCategoryAndIdLessThanOrderByIdDesc("avail",null,0, pageableObj);

In this case, Spring will return the fields where category is null and match the rest of the criteria.

What I'd like to achieve is, when passing null, I want Spring to kind of ignore it and return all the values for that specific field.

I know I can achieve this by writing a SQL @Query above the function, but I want to know if there is no way of adding a condition check in the JPA query itself.

Zoe Lubanza
  • 164
  • 2
  • 2
  • 1
    Did you read https://stackoverflow.com/questions/43780226/spring-data-ignore-parameter-if-it-has-a-null-value ? – TomStroemer May 22 '23 at 15:01
  • 2
    If you pass `null`, it will be literal. If you want to ignore it, create another method i.e. `findAllByAvailabilityAndIdLessThanOrderByIdDesc` without `AndItemCategory` in the name. Create a service method that checks for `null` and call the appropriate repository method. – Mr. Polywhirl May 22 '23 at 15:01
  • you can use the Specification feature provided by Spring Data JPA. Here is examples how to use it https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl . **NOTE: Specification adds an extra layer of abstraction and complexity to your code** – Feel free May 22 '23 at 15:03
  • You can check https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.matchers. – Wansu yang May 22 '23 at 15:14
  • What @Mr.Polywhirl said, if it is optional then make another method without that parameter. – Bill Mair May 22 '23 at 23:18

0 Answers0