Spring数据分页并排序NamedNativeQuery(JPA-Hibernate-MySql)

时间:2019-03-11 16:10:19

标签: java spring-data-jpa

我在Spring Data(JPA Hibernate MySQL)应用程序中将NamedNativeQueries与SqlResultSetMappings一起使用,并且分页成功,但排序没有成功。

我尝试了两种查询形式:

@NamedNativeQuery(
  name = "DatasetDetails.unallocatedDetailsInDataset",
  resultClass = DatasetDetails.class,
  resultSetMapping = "DatasetDetails.detailsForAllocation",
  query = "SELECT dd.id, fk_datasets_id, fk_domains_id, fk_sources_id, dom.name AS domain, " +
  "src.name AS source " +
  "FROM datasets AS d " +
  "JOIN datasets_details AS dd ON dd.fk_datasets_id = d.id " +
  "JOIN sources AS src ON src.id = dd.fk_sources_id " +
  "JOIN domains AS dom ON dom.id = dd.fk_domains_id " +
  "WHERE fk_datasets_id = :datasetId " +
  "AND dd.id NOT IN (" +
  "SELECT fk_datasets_details_id from allocations_datasets_details)  \n/* #page */\n"),

,第二个只是在第二个查询上使用计数符号,而不是使用#page符号。

@NamedNativeQuery(
  name = "DatasetDetails.unallocatedDetailsInDataset.count",
  resultClass = DatasetDetails.class,
  resultSetMapping = "DatasetDetails.detailsForAllocation",
  query = "SELECT count(*)
....

这两种方法均可用于分页,但排序将被忽略。

这是存储库:

public interface DatasetDetailsRepository extends PagingAndSortingRepository<DatasetDetails, Long> {
    @Query(nativeQuery = true)
    List<DatasetDetails> unallocatedDetailsInDataset(@Param("datasetId") long datasetId,
                                                     @Param("page") Pageable page);
}

可分页页面的组装方式如下:

Sort sort = Sort.by(Sort.Order.asc(DatasetDetails.DOMAIN), Sort.Order.asc(DatasetDetails.SOURCE));
Pageable page = PageRequest.of(page, limit, sort);

不会引发任何错误,但是排序不会完成,并且不会生成ORDER BY。

明确添加诸如ORDER BY#{#page}之类的内容不会编译。

1 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,我不得不使用NamedNativeQuery对不同的列和方向进行动态过滤/排序;显然,排序被忽略了。我发现了这种解决方法,虽然不一定很好,但确实可以完成工作:

对于存储库:

List<MyEntity> findMyEntities(
    @Param("entityId") long entityId,
    @Param("sortColumn") String sortColumn,
    @Param("sortDirection") String sortDirection,
    Pageable page);

本机查询如下:

@NamedNativeQueries({
  @NamedNativeQuery(name = "MyEntity.findMyEntities",
      query = "select e.field1, e.field2, ..." +
              " from my_schema.my_entities e" +
              " where condition1 and condtition2 ..." +
              " order by " +
              "   CASE WHEN :sortColumn = 'name'      and :sortDirection = 'asc'  THEN e.name      END ASC," +
              "   CASE WHEN :sortColumn = 'birthdate' and :sortDirection = 'asc'  THEN e.birthdate END ASC," +
              "   CASE WHEN :sortColumn = 'name'      and :sortDirection = 'desc' THEN e.name      END DESC," +
              "   CASE WHEN :sortColumn = 'birthdate' and :sortDirection = 'desc' THEN e.birthdate END DESC" +
  ),
  @NamedNativeQuery(name = "MyEntity.findMyEntities.count",
          query = "select count(*) from my_schema.my_entities e" +
                  " where condition1 and condtition2 ..." +
                  "  and :sortColumn = :sortColumn and :sortDirection = :sortDirection"
  )
})

计数查询中的通知我为:sortColumn:sortDirection使用2个冗余条件,因为一旦在存储库函数中指定为@Param,就需要在实际查询中使用它们

在调用函数时,在我的服务中,我有一个指示方向的布尔值和一个指示排序列的字符串,如下所示:

public Page<MyEntity> serviceFindFunction(Long entityId, String sortColumn, Boolean sortDirection, Integer pageNumber, Integer pageSize) {
    String sortDir = (sortDirection) ? 'asc' : 'desc';
    Pageable pageable = new PageRequest(pageNumber, pageSize); // Spring Data 1.0 syntax

    // for Spring Data 2.0, as you were using, simply:
    // Pageable pageable = PageRequest.of(pageNumber, pageSize);

    return entityRepository.findMyEntities(entityId, sortColumn, sortDir, pageable)
}

我对此不满意的2件事是count查询中sortColumnsortDirection参数的冗余用法,以及我按语句编写订单的方式。之所以使用单独的CASE语句,是因为我对排序的列具有不同的数据类型,并且如果它们不兼容(例如nvarchardate),则查询将失败错误:

  

Conversion failed when converting date and/or time from character string

我也可能嵌套条件,即首先为方向创建一个案例,为列创建一个内部案例,但是我的SQL技能仅走了这么远。

希望这会有所帮助!任何反馈或改进都非常欢迎。