postgresqlspring-data-jpa

Spring Data JPA with Postgesql and native query with Sort.by creates a wrong SQL query


I have repository with a native query like this:

@Query(value = """
        SELECT p.*
        FROM parent p
                 JOIN (SELECT parent_id, sum(amount) AS total_amount
                       FROM child
                       GROUP BY parent_id) c ON p.id = c.parent_id
        WHERE p.number = :number
          AND p.diff != 0
          AND p.diff <> total_amount;
        """, nativeQuery = true)
Page<ParentEntity> findAllWithDiffByNumber(@Param("number") String number, Pageable paging);

I setup paging like this:

PageRequest pageRequest = PageRequest.of(1, 10, Sort.by(Sort.Direction.DESC, "endDate"));

When I call it, following error appears:

org.springframework.dao.InvalidDataAccessResourceUsageException: JDBC exception executing SQL [SELECT p.*
FROM parent p
     JOIN (SELECT parent_id, sum(amount) AS total_amount
           FROM child
           GROUP BY parent_id) c ON p.id = c.parent_id
WHERE p.number = ?
  AND p.diff != 0
  AND p.diff <> total_amount offset ? rows fetch next ? rows only;
 order by p.endDate desc] [ERROR: syntax error at or near "order"
  Position: 3] [n/a]; SQL [n/a]

The problem is clearly with my PageRequest since spring creates this weird construct:

...offset ? rows fetch next ? rows only;order by p.endDate desc

First of all, there is a semicolon between fetch and order commands, second, it's in the wrong order. Correct syntax is:

...order by period.end_date desc offset ? rows fetch next ? rows only

Is it a bug or am I doing anything wrong?


Solution

  • AND p.diff <> total_amount ;
    

    You should not have ; at the end of the query.