Description
Description of Pageable.Sort problem
Introduction
I have a controller where @SortDefault
is used.
@SortDefault(sort="updated", direction = Sort.Direction.DESC) Pageable pageable
There are 2 separate entities without connection. There is a query in DocumentRepository
(JpaRepository) in which both entities are used.
@Query("select d from Document d where " +
"(:name is null or d.name = :name) and " +
"(:machineExternalId is null or exists (select machine.id from Machine machine where machine.externalId = :machineExternalId))"
)
Page<DocumentEntity> findAllBy(String name, String machineExternalId, Pageable pageable);
In real application this query is much more complicated, I simplify this query for example application.
Problem report
Before Spring Boot 2.6.7 and 2.5.13 this query generated this SQL statement.
select documenten0_.id as id1_0_, documenten0_.name as name2_0_, documenten0_.updated as updated3_0_ from document documenten0_ where (? is null or documenten0_.name=?) and (? is null or exists (select machineent1_.id from machine machineent1_ where machineent1_.external_id=?)) order by documenten0_.updated desc limit ?
As you can see the sql statement ends with order by documenten0_.updated
. This is expected behaviour. After upgrading to Spring Boot 2.6.7 or 2.5.13 QuerySyntaxException is thrown instead.
org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'machine.updated'
[select d from org.example.entity.DocumentEntity d where
(:name is null or d.name = :name) and
(:machineExternalId is null or exists (select machine.id from org.example.entity.MachineEntity machine where machine.externalId = :machineExternalId))
order by machine.updated desc]
As you can see the problem is that the query ends with order by machine.updated
. This is not OK. Incorrectly machine entity is used.
Example project
I attach maven project (as simple as possible) in which the problem can be debug.
You can see in pom.xml
tested spring boot versions and the results of my tests.
<!-- <version>2.6.7</version> PROBLEM -->
<!-- <version>2.6.6</version> OK -->
<!-- <version>2.6.5</version> OK -->
<!-- <version>2.6.1</version> OK -->
<!-- <version>2.5.13</version> PROBLEM -->
<!-- <version>2.5.12</version> OK -->
<!-- <version>2.4.10</version> OK -->