Spring Data Jpa本地查詢(帶分頁方式)


https://blog.csdn.net/tyyytcj/article/details/78152524

 

Spring Data Jpa本地查詢(帶分頁方式)

在利用spring data jpa開發的時候為了解決一些復雜的查詢需求這時候我們需要引入本地查詢nativeQuery 
參照官方的例子

Native queries 
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.

Example 50. Declare a native query at the query method using @Query

public interface UserRepository extends JpaRepository<User, Long> { @Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true) User findByEmailAddress(String emailAddress); }

這是官方給出的使用本地查詢的例子,但是也特別說明了目前本地查詢並不支持動態排序,但是可以利用本地查詢進行分頁 
Note, that we currently don’t support execution of dynamic sorting for native queries as we’d have to manipulate the actual query declared and we cannot do this reliably for native SQL. You can however use native queries for pagination by specifying the count query yourself: 
這是官方給出的本地查詢的分頁形式 
注意:如果你用這種方式在進行分頁查詢時是會報錯的(測試數據庫為Oracle,其他數據庫暫未做測試) 
Example 51. Declare native count queries for pagination at the query method using @Query

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

我的代碼如下

@Query(value = "select * from secondleveldesc sd left join secondlevel s on s.code=sd.code ", countQuery = "select count(*) from secondleveldesc", nativeQuery = true) Page<SecondleveldescEntity> findAll(Pageable pageable);

此時的錯誤信息如下

Caused by: org.springframework.data.jpa.repository.query.InvalidJpaQueryMethodException: Cannot use native queries with dynamic sorting and/or pagination in method public abstract org.springframework.data.domain.Page com.material.cltx.dao.SecondlevelDescDao.findAll(org.springframework.data.domain.Pageable)

通過各種搜索最終找到一種解決辦法

    @Query(value = "select * from secondleveldesc sd left join secondlevel s on s.code=sd.code ORDER BY ?#{#pageable}",countQuery = "select count(*) from secondleveldesc",nativeQuery = true) Page<SecondleveldescEntity> findAll(Pageable pageable);

在查詢語句后面加上

ORDER BY ?#{#pageable}”

這樣就能順利的利用本地查詢進行分頁了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM