spring-projects / spring-projects/spring-data-jpa

Dynamic sorting presence detection inside Pageable before NativeQuery execution [DATAJPA-1590]

Open
#1,898 0 comments 0 reactions 1 assignee View on GitHub

@schauder is already working on this.

Since Dec 30, 2020.

type: enhancement
Dominant language
Java
Stars
3.3k
Forks
1.6k
PR merge metrics
No merged PRs in 30d

Description

Roman Golovan opened DATAJPA-1590 and commented

Example 59 under https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#_native_queries.

A Pageable object can be constructed having a Sort argument:

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

...

Pageable pageable = Pagerequest.of(page, size, sort);
userRepository.findByLastname("name", pageable);

 In this case the initial native query will be enriched with what Sort defines, which contradicts with what the documentation says:

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.

Moreover there leads to another issue, which is caused by the absence of logical to physical conversion happening when NativeQuery is enriched with Sort, so the following example fails:

@Entity
public class User {
 ...
 @Column(name = "user_name")
 private String userName;
 ...
}

public interface UserRepository extends JpaRepository<User, Long> { 

 @Query(value = "SELECT * FROM USERS", countQuery = "SELECT count(*) FROM   USERS", nativeQuery = true)
 Page<User> findPageableBy(Pageable pageable);
}
...
Pageable pageable = Pagerequest.of(page, size, Sort.by(Sort.Order.desc("userName")));
userRepository.findPageableBy(pageable);

The resulting query is somewhat like:

Resulting query is somewhat like:
 select id,
 user_name,
 ... from users order by userName desc limit ?
-----
userName cannot be mapped to user_name

 


Affects: 2.1.10 (Lovelace SR10)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.