2017-07-27 47 views
1

我使用Spring JPA來管理PostgreSQL數據。這些數據大量使用PostgreSQL中的jsonb數據類型9.4Spring JPA使用PostgreSQL進行排序和分頁JSONB

我的表(稱爲jobtable),簡化看起來是這樣的:

id, bigint | data, jsonb 
-------------------------------- 
1   | {"name": "Hello"} 
2   | {"name": "Testing"} 

使用Spring JPA,我定義爲了使某些查詢該表CrudRepository接口。對於jsonb具體的事情,我使用nativeQuery = true,以便我可以使用這種PostgreSQL類型。

例如,我可以查詢我的財產,像這樣:

@Query(
value = "select * from jobtable where data ->> 'name' = ?1", 
nativeQuery = true) 
JobEntity getJobByName(String name); 

此查詢的工作就好了。

當我嘗試使用jsonb的本機查詢使用分頁時,出現了我的問題。我的查詢是這樣的:

@Query(
value = "select * from jobtable \n#pageable\n", 
countQuery = "select count(*) from jobtable", 
nativeQuery = true) 
Page<JobEntity> getJobList(Pageable pageable); 

我包括Pageable參數和調用功能,例如:

Pageable pageable = new PageRequest(0, 10, Direction.DESC, "data ->> 'name'"); 
Page<JobEntity> results = myDao.getJobList(pageable); 

此代碼不能正常工作,併產生以下錯誤:

org.springframework.dao.InvalidDataAccessApiUsageException: 
Sort expression 'data ->> 'name': DESC' must only contain property references or aliases used in the select clause. If you really want to use something other than that for sorting, please use JpaSort.unsafe(…)! 

我不知道該怎麼做這個錯誤。我認爲這與對PageRequest對象中的sortBy參數的不正確理解有關,但我不確定當我打算對我的jsonb對象中的某個鍵排序時,如何構造該對象。

我可以構建原始SQL到PostgreSQL,看起來像select * from job order by data ->> 'jobId' desc limit 10但我寧願使用Pageable接口與Spring JPA這樣我就可以使用@Query符號,而不必在代碼中明確定義什麼自己。

回答

3

嘗試創建可分頁如下:

Pageable p = PageRequest.of(1,10, 
      JpaSort.unsafe(Direction.DESC, "data->>'name'")); 

這應該擺脫異常。

相關問題