我正在使用 Spring JPA 来管理我的 PostgreSQL 数据。此数据大量使用了 PostgreSQL 9.4
中的 jsonb
数据类型。
我的表(称为 jobtable
),简化后看起来像这样:
id, bigint | data, jsonb
--------------------------------
1 | {"name": "Hello"}
2 | {"name": "Testing"}
使用 Spring JPA,我定义了一个 CrudRepository
接口(interface),以便对该表进行一些查询。对于 jsonb
特定的事情,我使用 nativeQuery = true
以便我可以使用这种 PostgreSQL 类型。
例如,我可以这样查询我的属性(property):
@Query(
value = "select * from jobtable where data ->> 'name' = ?1",
nativeQuery = true)
JobEntity getJobByName(String name);
这个查询工作得很好。
当我尝试使用 jsonb
对 native 查询使用分页时,我的问题就出现了。我的查询是这样的:
@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
参数有关,但我不确定如何构造该 PageRequest
对象当我打算对 jsonb
对象中的键进行排序时。
我可以将原始 SQL 构建到 PostgreSQL,看起来像 select * from job order by data ->> 'jobId' desc limit 10
但我宁愿使用 Pageable
与 Spring JPA 的接口(interface),这样我就可以使用 @Query
符号,而不必自己在代码中明确定义任何内容。
最佳答案
尝试按如下方式创建 Pageable:
Pageable p = PageRequest.of(1,10,
JpaSort.unsafe(Direction.DESC, "data->>'name'"));
这应该会消除异常。
关于postgresql - 使用 PostgreSQL JSONB 的 Spring JPA 排序和分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45358010/