Spring Data Rest + Spring Boot - findBy *没有将参数传递给MongoDB?

时间:2015-03-20 14:02:44

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

我有一个使用spring-data-rest项目的spring boot web应用程序(带有jetty),我无法从GET请求中获取传递给mongo查询的参数。

我确定我做错了什么,但需要一些指导。

TL; DR ... search / query =>

$ http GET localhost:8080/rules/search/findByName?test2  # <-- NOTE 'test2'
HTTP/1.1 200 OK
Content-Type: application/hal+json; charset=UTF-8
Date: Fri, 20 Mar 2015 13:54:35 GMT
Server: Jetty(9.2.9.v20150224)
Transfer-Encoding: chunked
X-Application-Context: application

{}

Mongo saw =&gt;

> db.system.profile.find({op:"query", ns: "test.rule"}, {query: 1}). sort({ts:-1}).pretty()
{ "query" : { "name" : null } }    # <-- Note *NOT* 'test2'

更长的故事......

我有一个简单的“规则”类,只有id和名称。

public class Rule {
    private String id;
    private String name;
// getters/setters removed for brevity.
}

我的存储库公开了findByName()方法。

@RestResource
interface RuleRepository extends CrudRepository<Rule, String> {
    List<Rule> findByName(@Param("name") String name)
}

当我发布到春季启动应用程序时,它工作正常。我可以完美地看到mongo数据库中的数据。

(使用httpie应用程序发布...)

$ http POST localhost:8080/rules name="test2"
HTTP/1.1 201 Created
Content-Length: 0
Date: Fri, 20 Mar 2015 13:49:02 GMT
Location: http://localhost:8080/rules/550c254e87867064832263b3
Server: Jetty(9.2.9.v20150224)
X-Application-Context: application

...蒙戈

> db.rule.find({})
{ "_id" : ObjectId("550c254e87867064832263b3"), "_class" : "<package>.Rule", "name" : "test2" }

到目前为止看起来还不错。

$ http GET localhost:8080/rules
HTTP/1.1 200 OK
Content-Type: application/hal+json; charset=UTF-8
Date: Fri, 20 Mar 2015 13:51:36 GMT
Server: Jetty(9.2.9.v20150224)
Transfer-Encoding: chunked
X-Application-Context: application

{  "_embedded": { "rules": [  ... brevity.  Everything is here that should be ...

搜索资源看起来还不错。

$ http GET localhost:8080/rules/search
HTTP/1.1 200 OK
Content-Type: application/hal+json; charset=UTF-8
Date: Fri, 20 Mar 2015 13:51:47 GMT
Server: Jetty(9.2.9.v20150224)
Transfer-Encoding: chunked
X-Application-Context: application

{
    "_links": {
        "findByName": {
            "href": "http://localhost:8080/rules/search/findByName{?name}",
            "templated": true
        }
    }
}

但是当我搜索时,没有任何内容返回,并且mongo报告该查询已被传递为null。

$ http GET localhost:8080/rules/search/findByName?test2
HTTP/1.1 200 OK
Content-Type: application/hal+json; charset=UTF-8
Date: Fri, 20 Mar 2015 13:54:35 GMT
Server: Jetty(9.2.9.v20150224)
Transfer-Encoding: chunked
X-Application-Context: application

{}

...蒙哥

> db.system.profile.find({op:"query", ns: "test.rule"}, {query: 1}). sort({ts:-1}).pretty()
{ "query" : { "name" : null } }

1 个答案:

答案 0 :(得分:2)

您的请求应为localhost:8080/rules/search/findByName?name=test2。正如HATEOAS的{​​{1}}回复中所述:

localhost:8080/rules/search

{ "_links": { "findByName": { "href": "http://localhost:8080/rules/search/findByName{?name}", "templated": true } } } findByName{?name}