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?

3
  • @KrishnaKuntala but spring data-jpa will implement out of the box right Commented Jun 26, 2017 at 9: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. Commented Jun 26, 2017 at 9:58
  • Possible duplicate of JPA Query to handle NULL parameter value Commented Feb 13, 2018 at 7:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes. name and age are request parameters. They can be null and if so it should return the complete users list
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.
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<User> findByStateIdAndAge(Integer stateId, Integer age, Pageable pageable);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.