5

I m using Spring Data Rest JPA which implements the Query internally on the basis of method name.

I wrote the following method in my repository interface which should list all the users in a state and if the name and/or age is present, it should filter the result.

StateId is mandatory but name and age are optional filter parameters

public List<User> findByStateIdAndNameOrAge(Integer stateId, String name , Integer age, Pageable pageable);

I am not getting any results. Where am I doing wrong?

Community
  • 1
  • 1
zilcuanu
  • 3,451
  • 8
  • 52
  • 105
  • @KrishnaKuntala but spring data-jpa will implement out of the box right – zilcuanu Jun 26 '17 at 09:56
  • 1
    I think your query is probably interpreted as : (StateId And name) OR Age which is not what you want. Your best choice would be to use criteria api or create dynamic query as your query is changing at runtime function of your optional parameters. – Abass A Jun 26 '17 at 09:58
  • Possible duplicate of [JPA Query to handle NULL parameter value](https://stackoverflow.com/questions/28554798/jpa-query-to-handle-null-parameter-value) – Jens Schauder Feb 13 '18 at 07:34

1 Answers1

1

You can try

There is no mistake in your method defination.

public List<User> findByStateIdAndNameOrAge(Integer stateId, String name , Integer age, Pageable pageable);

but you can't pass null parameter to this method so it will not work if you are putting any parameter is blank.

Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25
  • Yes. name and age are request parameters. They can be null and if so it should return the complete users list – zilcuanu Jun 26 '17 at 10:33
  • The other way is that you can figure out before hitting an API that which parameters you are getting null and depending on it you can call different API. – Amit Gujarathi Jun 26 '17 at 10:36
  • For example if you get that the name is blank then you should fire an API which don't have name as input parameter. simply just remove the API parameter which is null . For this you should fire an API as public List findByStateIdAndAge(Integer stateId, Integer age, Pageable pageable); – Amit Gujarathi Jun 26 '17 at 10:38