Evan_HZY
Evan_HZY

Reputation: 1024

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!

Upvotes: 8

Views: 8908

Answers (3)

Tanmay Delhikar
Tanmay Delhikar

Reputation: 1387

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")

Upvotes: 4

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

You are already passing a Pageable object. You can pass your params as follows

new PageRequest(1, 10, Sort.Direction.ASC, "yourProperty");

Upvotes: 4

John Bollinger
John Bollinger

Reputation: 181008

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

In JPA (and JDBC) parameters are placeholders for values, not for more general query text. You cannot use them in place of identifiers such as column or table names, nor in place of keywords such as ASC / DESC.

Queries that have similar form but differ in one or more identifiers or keywords are fundamentally different queries. You need different Querys to represent them.

Upvotes: 2

Related Questions