Spring jpa jpql query

I was wondering if it is possible to execute a jpql request in a spring jpa repository and be able to use paging as a sort function, as it might donde with example and spec. I would like to do something like:

findAll(String jpql, Pageable pageable)

      

QueryByExampleExecutor interface, i.e. announces:

findAll(Example<S> example, Pageable pageable);

      

The JpaSpecificationExecutor interface declares:

Page<T> findAll(Specification<T> spec, Pageable pageable);

      

+3


source to share


1 answer


According to Spring Data Documentation, this should be possible even with native queries. Take a look at example 51:

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);
}

      



Sorting is also possible by documentation :

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.lastname like ?1%")
  List<User> findByAndSort(String lastname, Sort sort);

  @Query("select u.id, LENGTH(u.firstname) as fn_len from User u where u.lastname like ?1%")
  List<Object[]> findByAsArrayAndSort(String lastname, Sort sort);
}

      

0


source







All Articles