【问题标题】:Spring Boot data, MongoDB not returning resultsSpring Boot数据,MongoDB不返回结果
【发布时间】: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


【解决方案1】:

我的 MongoConfiguration 没有被选中,所以我在 application.properties 中添加了详细信息:

spring.data.mongodb.database=itemdb

这解决了问题,现在我可以从我的查询中获取所有项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2015-11-26
    • 2021-11-23
    • 1970-01-01
    • 2016-07-01
    • 2017-08-29
    • 2018-10-02
    相关资源
    最近更新 更多