Search code examples
javaspringspring-bootjpql

Spring Boot @Query: Order by named parameter


I like my REST-Api endpoint to be sortable by diffrent model attributes. I have googled a lot of solutions, but none of them fit to my requirements.

What I like to have is something like the following within my PagingAndSortingRepository interface:

    @Query(value = "SELECT v FROM vwFact v WHERE v.applicationId like %:applicationId% " +
            "and (v.mdName01 like :mdName% or v.mdName02 like :mdName% or v.mdName03 like :mdName% or v.mdName04 like :mdName%) " +
            "ORDER BY :sortParam :sortDir"
    )
    Page<vwFact> findAllByApplicationIdAndMdName(
            @Param(value = "applicationId") String applicationId,
            @Param(value = "mdName") String mdName,
            @Param(value = "sortParam") String sortParam,
            @Param(value = "sortDir") String sortDir,
            Pageable pageable
    );

Is there a chance to implement that, or do I have to do this I an other way. What would you recomment?


Solution

  • Pageable has an option to specify how to sort the results (both direction and params).

    PageRequest(int page, int size, Sort sort) 
    PageRequest(int page, int size, Sort.Direction direction, String... properties)