2017-06-27 159 views
3

我想知道是否能夠通過一個彈簧JPA儲存庫來執行JPQL查詢和能夠使用尋呼作爲排序功能,因爲它可以與實施例規格東德。我想這樣做:彈簧JPA JPQL查詢

findAll(String jpql, Pageable pageable) 

QueryByExampleExecutor接口即聲明:

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

JpaSpecificationExecutor接口聲明:

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

回答

0

按照Spring Data documentation它應該是可能的,即使與原生查詢。看一看例如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); 
} 

排序似乎也可以按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

感謝的答案,但我一直在尋找的是動態創建查詢,並在代碼中調用庫,你的選擇所需的查詢已經預定義 – jcrada

+0

即時編寫JPQL,可能會有問題。 JPQL是在運行時編譯的,但只能在類加載階段進行編譯,所以如果出現錯誤,您的存儲庫將無法加載。這是一個很好的安全措施。您可以嘗試使用Criteria Query:https://stackoverflow.com/questions/28874135/dynamic-spring-data-jpa-repository-query-with-arbitrary-andclauses –