【问题标题】:Spring Data REST: repository multiple value request parametersSpring Data REST:存储库多值请求参数
【发布时间】:2017-01-08 04:09:38
【问题描述】:

谁能帮帮我?事实上,我有一个使用 Spring boot/Spring Data-REST 的项目。在我的自定义存储库界面中,我创建了一个新方法,如下所示:

@Query("SELECT h FROM History h WHERE " +
        " (:fromDate IS NULL OR h.date >= :fromDate)" +
        " AND (:toDate IS NULL OR h.date <= :toDate)" +
        " AND (:ids IS NULL OR h.id IN :ids)")
 Page<History> findHistoryByCriteria(
        @Param("fromDate") @DateTimeFormat(pattern = "MM/dd/yyyy") Date fromDate,
        @Param("toDate") @DateTimeFormat(pattern = "MM/dd/yyyy") Date toDate,
        @Param("ids") List<Integer> ids);

当我使用 URL http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids[]=1&ids 调用它时[]=2,我得到错误的结果。在日志中我得到

TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [5] as [INTEGER] - [null]
TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [6] as [INTEGER] - [null]

如果我尝试使用 http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids=2,它返回了一个有效的结果。

如果我尝试使用 http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids=2&ids=3强>,我得到一个例外

 nested exception is java.lang.IllegalArgumentException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]

我应该如何调用包含多值参数(数组)的 URL,或者我应该怎么做才能使其将参数视为数组或集合?

提前谢谢你。

【问题讨论】:

  • 终于看到怎么解决了。对于遇到相同问题的每个人,使用 Spring 发送数组值的 URL 格式是 ids=oneId,anotherId 而不是 ids[]=oneId&ids[]=anotherId 或 ids=oneId&ids=anotherId

标签: spring spring-mvc spring-boot spring-data-jpa spring-data-rest


【解决方案1】:

对于那些在问这个问题几年后来到这里的人,由于它是谷歌搜索结果的顶部,我遇到了同样的问题并想出了以下几点:

如果您在存储库方法中使用 Collection 类型作为参数,则让 SD Rest 正确转换它的唯一方法是将值作为逗号分隔的字符串传递到单个查询参数中,如 Rindra 上述注释所述。它不会接受具有不同值的多个同名参数。这是因为转换代码不够聪明,无法知道它提供的集合(例如 List)与预期的集合(例如 List)不同,因为它不查看内部集合类型。它只是看到需要一个 List 并且提供了一个 List,因此它会跳过任何转换尝试。

也就是说,如果您改为使用数组 (Integer[]) 而不是集合,那么您可以将值作为逗号分隔的字符串传递给单个查询参数,并作为单个值传递给多个查询参数。

这取决于转换服务中可用的注册转换器。在 "?ids=123,432" 的情况下有一个 StringToCollectionConverter 在 "?ids=123&ids=432" 的情况下有一个 CollectionToArrayConverter

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 2017-12-02
    • 2017-10-18
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2016-07-06
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多