Sprint Data Rest是否支持开箱即用的列查询?

问题描述 投票:0回答:1

我有一个非常简单的例子,它使用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查询是否应该开箱即用?

/人?的firstName = FN

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

毋庸置疑,它对我不起作用,但我看到有关如果它是开箱即用支持的相互矛盾的信息。

提前致谢,

rest jpa spring-data-rest
1个回答
0
投票

我的问题是,以下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将自动公开此方法作为一个终点。

例如,如果你编写一个方法,如:List findByNameContains(String name);

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

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

© www.soinside.com 2019 - 2024. All rights reserved.