Skip to content

Native query with #sort generates a broken query #3546

Closed
@paulbakker

Description

@paulbakker

Although the docs mention that dynamic sorting is not supported with native queries, the following almost works:

 @Query(
            nativeQuery = true,
            value = "select * from show #sort"
    )
    List<Show> showsNativeWithoutWorkaround(Sort sort);

It generates the following query when sorting by a title field: select * from show #sort ORDER BY title asc.
Note that it added the correct ORDER BY, but didn't remove the #sort placeholder.

I've created a simple example to reproduce here: https://github.com/paulbakker/spring-data-jpa-sort-bug.
See the README for details about the code.

The example uses a Postgres Testcontainer, so no extra setup is needed.

A hacky workaround is to add a custom query rewrite like this:

public class SortFixQueryRewriter implements QueryRewriter {
    @Override
    public String rewrite(String query, Sort sort) {
        return query.replace("#sort", "");
    }
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions