Search code examples
mysqlquerydsl

How can I sort by field position in querydsl?


In JPQL I can use the following select u from Entity u order by u.field1, 1.
This ensures that the back-end mysql database will always return the result in the exact same order (e.g. in case u.field1 has duplicates).
At position 1 I always keep the PK(id).

How can I achieve the same (use positional sorting) with querydsl?

P.S. Sorting code is dynamically generated, so I want to avoid the requirement to provide the PK as an extra parameter to the SortUtil.


Solution

  • From what I understand, your requirement is to order by a database column, then by a number you provide as an argument. I think this will work, I've passed 1L into Expressions.constant but obviously replace this with your dynamically generated field.

    .orderBy(someRelationalPathBase.field1.asc(), new OrderSpecifier<>(Order.ASC, Expressions.constant(1L)))