Mehmet Sezer
Mehmet Sezer

Reputation: 133

Spring Neo4j JPA native dynamic order by query

I need to sort native query dynamically, I passed the Pageable object, skip and limit properties work correctly when I assigned $skip and $limit parameters to the native query. But I couldn't use order by statements such as "ORDER BY m.title DESC". My actual query is more complicated than this but I just wrote the basics version of the actual query.

Repository

@Query(value = "MATCH (m:Movie) RETURN m SKIP $skip LIMIT $limit;", countQuery = "MATCH (m:Movie) RETURN count(m);")
Page<Movie> getMoviesBy(Pageable pageable);

Service

return repository.getMoviesBy(pageable);

Controller

 @GetMapping("search")
    public ResponseEntity search(@RequestParam(defaultValue = "0") Integer pageNo,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 @RequestParam Sort.Direction sortDirection,
                                 @RequestParam String sortBy
    ) {
        return ResponseEntity.ok(movieService.search(PageRequest.of(pageNo, pageSize,Sort.by(sortDirection, sortBy))));
    }

Upvotes: 3

Views: 735

Answers (2)

sourheart
sourheart

Reputation: 124

Use the the variable sortBy how parameter in the function service and repository, and use this variable for create a dinamic order in the native query.

Upvotes: 0

Related Questions