Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 292
Evan_HZY Avatar asked Jul 07 '17 18:07

Evan_HZY


3 Answers

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

like image 175
Tanmay Delhikar Avatar answered Nov 14 '22 22:11

Tanmay Delhikar


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

new PageRequest(1, 10, Sort.Direction.ASC, "yourProperty");
like image 39
Bunyamin Coskuner Avatar answered Nov 14 '22 21:11

Bunyamin Coskuner


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.

like image 27
John Bollinger Avatar answered Nov 14 '22 20:11

John Bollinger