【问题标题】:Does Sprint Data Rest support out of the box column queries?Sprint Data Rest 是否支持开箱即用的列查询?
【发布时间】:2019-04-15 15:25:42
【问题描述】:

我有一个使用 Spring Data Rest 和 JPA 公开人员资源的非常简单的示例。启动应用程序时,它按预期工作,我可以 POST 和 GET 资源实例。

向 /person 发送 GET 时,我收到以下响应:

    "_embedded": {
        "person": [
            {
                "firstName": "FN",
                "lastName": "LN",
                "_links": {
                    "self": {
                        "href": "http://localhost:9090/person/1"
                    },
                    "person": {
                        "href": "http://localhost:9090/person/1"
                    },
                    "address": {
                        "href": "http://localhost:9090/person/1/address"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:9090/person{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:9090/profile/person"
        },
        "search": {
            "href": "http://localhost:9090/person/search"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 1,
        "totalPages": 1,
        "number": 0
    }
}

如您所见,person 资源有一个值为 FN 的 firstName 属性。

我的问题是以下 GET 查询是否应该开箱即用?

/person?firstName=FN

或者这是否需要使用自定义搜索方法来实现?

不用说它不适合我,但我看到关于它是否支持开箱即用的相互矛盾的信息。

提前致谢,

【问题讨论】:

标签: rest jpa spring-data-rest


【解决方案1】:

我的问题是以下 GET 查询是否应该开箱即用?

没有。您将收到类似

的错误
{
"cause": {
"cause": null,
"message": "For input string: \"findByName\""
},
"message": "Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'findByName'; nested exception is java.lang.NumberFormatException: For input string: \"findByName\""
}

Spring Data Rest 具有以下 URL 结构。 /{pluralEntityName}/{primaryKey} 例如,当实体名称为 Person 且主键为 Long 时,它将是 /persons/1

我们看到此错误消息是因为 Spring Date Rest 尝试将实体名称之后的第二个参数转换为该实体的主键。在我的 Person 实体中,主键是 Long,因此它尝试将 findByName 转换为 Long 并失败。

或者这是否需要使用自定义搜索方法来实现?

是的,如果您想在存储库上进行搜索,您需要按照 Spring Data JPA 的方法名称约定在存储库中编写一个方法,然后 Spring Data JPA 会自动将此方法转换为 SQL 查询,Spring Data Rest 会自动将此方法公开为端点。

例如,如果您编写如下方法: 列出 findByNameContains(String name);

此方法将通过 Spring Data Rest 公开,您将能够从以下端点访问它: http://localhost:8080/persons/search/findByNameContains?name=Mahsum

顺便说一句,您可以访问http://localhost:8080/persons/search查看所有可用的搜索方法

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2011-03-28
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2013-09-17
    相关资源
    最近更新 更多