我使用Spring JPA来管理PostgreSQL数据。这些数据大量使用PostgreSQL中的jsonb
数据类型9.4
。Spring 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
符号,而不必在代码中明确定义什么自己。