0

I am using spring boot rest controller.

I use this Enum :

public enum Lang {
    EN,FR
}

my repository :

public List<Items> findByNameContainsAndLang(String name,Lang language);

my controller:

@RequestMapping(value = "/items", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ItemModel>> getSearchedItems(
            @RequestParam(name = "name", defaultValue = "",required = false) String name,
            @RequestParam(name = "language",required = false) Lang language
        ) { 
        return ResponseEntity.ok(itemServiceImp.findSearchedItem(name, language));  
}

this is my service :

public List<ItemModel> findSearchedItem(String name, Lang language ){
    List<ItemModel> lst=null;
    lst = itemRepo.findByNameContainsAndLang(name language)
                  .stream()
                  .map(this::mapItemModel)
                  .collect(toList());
    return lst;
}

so when I try this path:

http://myUrl/items?name=something&language=EN

that's retrieve the result and return my Data but when I try:

http://myUrl/items?name=something  
http://myUrl/items?language=EN 
http://myUrl/items

that retrieves 0 data and an empty List

Does anybody has an idea ,despite I use require=false in the @Requestparam Any help ? Thank you in advance

Ael9643
  • 3
  • 2

2 Answers2

0

The required = false means that the endpoint does not expect the parameter to be present. This has no influence on your query. Therefore currently, when you omit one of the values that value will be null. Resulting in no matches to be found.

To solve this, you can look at the JPA Criteria API, that will assist you in building queries that only have taken into account the populated values.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
Reg
  • 10,717
  • 6
  • 37
  • 54
0

@Reg is correct.

You can either use custom repository or try calling different repository methods depending upon the values of your name and language variables.

public List<ItemModel> findSearchedItem(String name, Lang language ) {
    List<ItemModel> list = null;
    if(name != null && language != null) { 
        list = findByNameContainsAndLang(String name,Lang language);
    } else if(name == null) { 
        list = findByLang(Lang language); //Add this method in your repo
    } else if(language == null){
        list = findByName(String name); //Add this method in your repo
    }
    return list;
}
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
  • I really used the same logic as you and it works but I think there is a lot of if else conditions I must refactoring the code – Ael9643 Dec 12 '18 at 11:49
  • You can otherwise use a CriteriaQuery. Check out [this](https://stackoverflow.com/a/44278967/3094731) link on how to use CriteriaQuery in JpaRepositories. – Abdullah Khan Dec 12 '18 at 11:58