I need to sort data on the back-end level using @RequestParam in native query Jpa

Pavel :

So, idea is simple, I need to have an back-end sorting and filtering URL, smth like that:

/users?find=Paul&sortBy=name:asc

So far I have this controller method:

@GetMapping("/users")
    public List<User> findUserByName(@RequestParam Optional<String> find,
                                     @RequestParam Optional<Integer> page,
                                     @RequestParam Optional<String> sort)
    {
        return userRepository.findByName(find.orElse("_"),
                new PageRequest(page.orElse(0),5,
                        Sort.Direction.ASC, sort.orElse("name")));
    }

And this UserRepository that extends JpaRepository:

@Query("select u from User u where name like %?1%")
    List<User> findByName(String name, Pageable pageable);

My question is: I am specifying the sort status (Ascending/Descending) in the Controller itself, but I want it to be specified in url, like here:

/users?find=Paul&sortBy=name:asc

but for now it works for me only like that

/users?find=Paul&sortBy=name

and it gets sorted in ascending order automatically, because I specified it in the Controller method.

Could You be so kind to explain me how can I do that, please :)?

Take care!

ArunKumar M N :

you can use Direction.fromString(order) method where order can be "asc" or "desc"

for order you should keep seperate param

@RequestParam Optional<String> order


userRepository.findByName(find.orElse("_"),
                new PageRequest(page.orElse(0),5,
                        Sort.Direction.fromString(order), sort.orElse("name")));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139447&siteId=1
Recommended