Search code examples
javamysqlspringspring-data-jpajpql

In JPA Query, can I pass the order by property and DESC/ASC order as parameters in the method signature?


I am using spring framework and working repository level implementations.

I have a class:

@Repository public interface MyClassReadRepository extends ReadRepository<MyClass, Integer>

In this class there is a method that looks like this:

@Query("SELECT a FROM MyClass a WHERE a.type IN :myType ORDER BY :someProperty :someOrder") Page<MyClass> findByTypeAndOrder(@Param("myType") List<MyType> myType, @Param("someProperty")String someProperty, @Param("someOrder")String someOrder, Pageable pageable)

But apparently the Query structure is wrong: ":someProperty" should be an identifier...

My question is: how to pass order and sort parameters in the example above?

Thanks in advance!


Solution

  • Use:

    PageRequest(page, size, direction, properties)
    

    Creates a new PageRequest with sort parameters applied. Parameters:

    page: zero-based page index. (like 5 or 10 etc)

    size: the size of the page to be returned. (like 50 or 100 etc)

    direction: the direction of the Sort to be specified, can be null. (like Sort.Direction.ASC)

    properties: the properties to sort by, must not be null or empty. (like "my column name")