【问题标题】:Rest API with Spring Data MongoDB - Repository method not working使用 Spring Data MongoDB 的 Rest API - 存储库方法不起作用
【发布时间】:2018-02-11 02:02:00
【问题描述】:

我正在使用 MongoDB 阅读和学习 Spring Boot 数据。我的数据库中有大约 10 条记录,格式如下:

{
    "_id" : ObjectId("5910c7fed6df5322243c36cd"),
    name: "car"
}

当我打开网址时:

http://localhost:8090/items

我得到了所有项目的详尽清单。但是,我想使用MongoRepository 的方法,例如findByIdcount 等。当我这样使用它们时:

http://localhost:8090/items/count
http://localhost:8090/items/findById/5910c7fed6df5322243c36cd
http://localhost:8090/items/findById?id=5910c7fed6df5322243c36cd

我得到一个 404。

我的设置是这样的:

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws IOException {
        SpringApplication.run(Application.class, args);
    }
}

@Document
public class Item implements Serializable {
    private static final long serialVersionUID = -4343106526681673638L;

    @Id
    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

@RepositoryRestResource(collectionResourceRel = "item", path = "items")
public interface ItemRepository<T, ID extends Serializable> extends MongoRepository<Item, String>, ItemRepositoryCustom {

}

我做错了什么?我需要实现MongoRepository 定义的方法还是会自动实现?我迷路了,长期以来一直试图弄清楚这一点。我的控制器中没有任何方法,它是空的。

【问题讨论】:

  • 您是否查看过应用程序启动时查看的请求映射?它将向您展示 Spring Data REST 自动创建的所有映射。
  • 请原谅错别字。那应该说“在您的应用程序启动时记录”
  • 谢谢安迪。 Eclipse 中是否有可以告诉我们所有映射的功能?抱歉,我不确定。

标签: mongodb spring-boot repository spring-data-mongodb mongorepository


【解决方案1】:

您必须声明 findById 方法才能公开它。

Item findById(String id);
Item findByName(String name);

请注意,您不需要实现这些方法。 SpringBoot 会分析方法名并提供正确的实现

【讨论】:

  • 它有效。但是,count 方法不能以这种方式工作。是不是因为返回类型是long而不是Long?
【解决方案2】:

我有同样的问题,

删除@Configuration,@ComponentScan 后一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2016-06-25
    • 2015-08-17
    • 2012-06-02
    • 2017-02-09
    相关资源
    最近更新 更多