使用Spring Data MongoDB的Rest API - 存储库方法不起作用

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

我正在阅读和学习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定义的方法,还是会自动实现?我迷失了,并且一直在努力解决这个问题。我的控制器中没有任何方法,它是空的。

mongodb spring-boot repository spring-data-mongodb mongorepository
2个回答
2
投票

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

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

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


0
投票

我有同样的问题,

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

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