Spring Data Rest - Parameters with default values

I created the following @RepositoryRestResource request where I want to create a dynamic request for my rest api. So basically I would like to do something like:

 myHost/myApp/data/search/all?name=me&age=20&address=myhome&etc=etc 

So, I created the query below:

  @Query("Select t from Data t " + "where " + "t.name like :name AND " + "t.age = :age AND " + "t.address = :address AND " + "t.etc= :etc" @RestResource(path = "all", rel = "all") Page findByAll(@Param("name") String name, @Param("age") String age, @Param("address") String address, @Param("etc") String etc, Page page); 

Obviously, some of them may not have been introduced. Is there a way to determine the default values ​​in the repository? Therefore, for example, I would like name have a default value of % .

I'm not quite sure that this approach is right for what I want to do, so any alternative suggestions are welcome.

+6
source share
3 answers

I know this is older, but I had a similar problem and it was solved as follows:

 @Query("Select t from Data t " + "where " + "(:name IS NULL or t.name like :name) AND " + "(:age IS NULL or t.age = :age) AND " + "(:address IS NULL or t.address = :address) AND " + "(:etc IS NULL or t.etc= :etc)") @RestResource(path = "all", rel = "all") Page findByAll(@Param("name") String name, @Param("age") String age, @Param("address") String address, @Param("etc") String etc, Page page); 
+7
source

Faced with the same problem, and as far as I can research, the best way to solve this is to make a different query for each set of values.

+1
source

So, one of the possible solutions could be that you can go to the controller and use your @Controller in your @Controller / @RequestParam with the required = false and defaultValue = "%" attributes.

The corresponding call might look like this:

 @RestController ... @RequestMapping(value = "[myCallFromFrontend]", method = RequestMethod.GET) public ResponseItem getItemsByFilters ( @RequestParam(required = false, defaultValue = "%") String name, @RequestParam(required = false, defaultValue = "%") String age, @RequestParam(required = false, defaultValue = "%") String address, @RequestParam(required = false, defaultValue = "%") String etc, HttpServletResponse response){ ResponseItem item = null; try { //you might do this in service layer. item = myRepository.findByAll(name, age, address, etc); } catch (myException mE) { log.error("...", mE); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return item; } 

So now you have set the default values. However, I do not know how to install them directly at the repository level. I created the question of what is right here

+1
source

Source: https://habr.com/ru/post/975058/


All Articles