Skip to content
Advertisement

Spring Pageable does not translate @Column name

I have Entity object :

JavaScript

And I have database view defined like this:

JavaScript

And I have repository with custom query:

JavaScript

Everything works fine when I request standard data with url: http://localhost:8080/someEntity/search/findBySomeParameter?parameter=25&page=0&size=20

But when I add sorting information it doesn’t work: http://localhost:8080/someEntity/search/findBySomeParameter?parameter=25&page=0&size=20&sort=entityFieldName,asc will throw following exception (I’m using Oracle database):

JavaScript

It seems like sorting field are not translated with @Column(name), but are inlined into SQL query.

Is there any way to make pageable sort translated, so that it will use not field name but column name?

Advertisement

Answer

This article sheds light on the issue. Read from section 3.1 on.

Apparently dynamic sorting is not supported for native queries. Actually, if you change your findBySomeParameter method to take a Sort instead of a Pageable you will get org.springframework.data.jpa.repository.query.InvalidJpaQueryMethodException: Cannot use native queries with dynamic sorting.

Using pageable you don’t get the exception, and pagination actually seems to work fine, but dynamic sorting does not substitute the column name as you found. Looks to me like the only solution is to use JPQL instead of native query, which is not a problem as long as the query you need to make is the one you provide. You would need to map the view though to a SomeEntityView class in order to use JPQL.

EDIT I thought the issue was not documented but it actually is here in the official doc

Spring Data JPA does not currently support dynamic sorting for native queries, because it would have to manipulate the actual query declared, which it cannot do reliably for native SQL. You can, however, use native queries for pagination by specifying the count query yourself, as shown in the following example:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement