【发布时间】:2018-02-11 01:29:27
【问题描述】:
我正在使用 MongoDB 阅读和学习 Spring Boot 数据。我的数据库中有大约 10 条记录,格式如下:
{
"_id" : ObjectId("5910c7fed6df5322243c36cd"),
name: "car"
}
以下是我的 Java/Spring 类:
@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 {
}
MongoDB 配置:
@Configuration
@EnableMongoRepositories
public class MongoConfiguration extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "itemdb";
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient("localhost", 27017);
}
@Override
protected String getMappingBasePackage() {
return "com.learning.domain";
}
}
我从 spring 开始关注文档,但是当我在浏览器中打开链接时:
http://localhost:1337/items
我的数据库中没有任何项目。我得到的只是:
{
"_embedded" : {
"item" : [ ]
},
"_links" : {
"self" : {
"href" : "http://localhost:1337/items"
},
"profile" : {
"href" : "http://localhost:1337/profile/items"
}
},
"page" : {
"size" : 20,
"totalElements" : 0,
"totalPages" : 0,
"number" : 0
}
}
_embedded 对象为空。我是否必须显式创建控制器并实现方法,还是 Spring-Data 自动执行?例如,我想获得计数,我这样做了:
http://localhost:1337/items/count
但它给了我一个 404。
【问题讨论】:
-
您是如何将项目添加到数据库中的?
-
使用 Mongobooster IDE。
-
我找到了解决方案。我的 MongoConfiguration 没有被选中。我在属性文件中添加了参数,现在它可以工作了。
标签: java spring mongodb spring-boot