Spring JPA使用PostgreSQL JSONB进行排序和分页

Pat*_*k D 3 postgresql spring-data-jpa jsonb postgresql-9.4

我正在使用Spring JPA来管理我的PostgreSQL数据.这些数据大量使用jsonbPostgreSQL 中的数据类型9.4.

我的表(称为jobtable)简化看起来像这样:

id, bigint | data, jsonb
--------------------------------
1          | {"name": "Hello"}
2          | {"name": "Testing"}
Run Code Online (Sandbox Code Playgroud)

使用Spring JPA,我定义了一个CrudRepository接口,以便对该表进行一些查询.对于jsonb特定的事情,我正在使用,nativeQuery = true以便我可以使用这种PostgreSQL类型.

例如,我可以这样查询我的属性:

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

这个查询工作得很好.

当我尝试使用Pagination与本机查询时,我的问题出现了jsonb.我的查询是这样的:

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

我包含Pageable参数并调用函数:

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

此代码不起作用,并产生以下错误:

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(…)!
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做这个错误.我认为这与sortByPageRequest对象中不正确地理解我的参数有关,但是PageRequest当我打算对我的jsonb对象中的键进行排序时,我不确定如何构造该对象.

我可以构建Raw SQL到PostgreSQL看起来像,select * from job order by data ->> 'jobId' desc limit 10但我宁愿使用PageableSpring JPA 的接口,这样我就可以使用@Query符号而不必自己在代码中明确定义任何东西.

Jac*_*000 8

尝试按如下方式创建Pageable:

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

这应该摆脱异常.

  • 对 Spring 5+ 没有帮助 (2认同)