0

I use JPA to a PostgreSQL DB with my repository

public interface MyRepository extends JpaRepository<...> {

  @Query(value = "SELECT * FROM my_table ORDER BY column1", nativeQuery = true)
  List<...> find1();

  @Query(value = "SELECT * FROM my_table ORDER BY ?1", nativeQuery = true)
  List<...> find2(String param);
}

find1() works fine: all rows are ordered by column1. But find2("column1") does not work.

How can I do it? I have to use native queries in any case, therefore I cannot resort to org.springframework.data.domain.Sort.

Johannes Flügel
  • 3,112
  • 3
  • 17
  • 32
  • Have you tried using named parameters? [https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.named-parameters](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.named-parameters) – Vitor Santos Feb 12 '19 at 16:47
  • @VitorSantos: Does not work, either. – Johannes Flügel Feb 12 '19 at 16:53
  • You cannot do it with parameters like this. Your options are to either create all the queries by which you will allow sorting in both directions and select based on that, or to use the CriteriaBuilder. Postgresql determines the sorting algorithm during parse time, so you cannot even use integer parameters to select it, even though you can use integers to choose the columns in raw queries. – coladict Feb 14 '19 at 08:46
  • I solved it by using `entityManager.createQuery(selfMadeHqlQuery)`. – Johannes Flügel Feb 14 '19 at 08:48

0 Answers0