Getting Started

引导设置工作环境的一种简便方法是通过 start.spring.io 创建基于 Spring 的项目或通过 Spring Tools 创建 Spring 项目。

An easy way to bootstrap setting up a working environment is to create a Spring-based project via start.spring.io or create a Spring project in Spring Tools.

Examples Repository

GitHub spring-data-examples repository 托管了多个示例,您可以下载和试用它们来了解库的工作原理。

The GitHub spring-data-examples repository hosts several examples that you can download and play around with to get a feel for how the library works.

Hello World

首先,你需要设置一个正在运行的 MongoDB 服务器。有关如何启动 MongoDB 实例的说明,请参阅 MongoDB Quick Start guide。安装后,启动 MongoDB 通常只需运行以下命令: /bin/mongod

First, you need to set up a running MongoDB server. Refer to the MongoDB Quick Start guide for an explanation on how to startup a MongoDB instance. Once installed, starting MongoDB is typically a matter of running the following command: /bin/mongod

然后,您可以创建一个 Person 类以存储:

Then you can create a Person class to persist:

Unresolved include directive in modules/ROOT/pages/mongodb/getting-started.adoc - include::example$example/Person.java[]

您还需要一个主应用程序来运行:

You also need a main application to run:

  • Imperative

  • Reactive

Unresolved include directive in modules/ROOT/pages/mongodb/getting-started.adoc - include::example$example/MongoApplication.java[]
Unresolved include directive in modules/ROOT/pages/mongodb/getting-started.adoc - include::example$example/ReactiveMongoApplication.java[]

当您运行主程序时,以上示例将产生以下输出:

When you run the main program, the preceding examples produce the following output:

10:01:32,265 DEBUG o.s.data.mongodb.core.MongoTemplate - insert Document containing fields: [_class, age, name] in collection: Person
10:01:32,765 DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "name" : "Joe"} in db.collection: database.Person
Person [id=4ddbba3c0be56b7e1b210166, name=Joe, age=34]
10:01:32,984 DEBUG o.s.data.mongodb.core.MongoTemplate - Dropped collection [database.person]

即便在这个简单的示例中,也有一些需要注意的地方:

Even in this simple example, there are few things to notice:

  • 你可以使用标准或响应式 MongoClient`对象以及要使用的数据库名称来实例化 Spring Mongo 的中央辅助类 `MongoTemplate

  • You can instantiate the central helper class of Spring Mongo, MongoTemplate, by using the standard or reactive MongoClient object and the name of the database to use.

  • 映射器针对标准 POJO 对象运行,无需任何其他元数据(不过你可以选择性地提供该信息。参见 here。)。

  • The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See here.).

  • 它使用约定来处理 id`字段,在存储到数据库中时将其转换为 `ObjectId

  • Conventions are used for handling the id field, converting it to be an ObjectId when stored in the database.

  • 映射约定可以使用字段访问。请注意, `Person`类只有获得器。

  • Mapping conventions can use field access. Notice that the Person class has only getters.

  • 如果构造函数参数名与存储文档的字段名称匹配,则使用它们来实例化对象。

  • If the constructor argument names match the field names of the stored document, they are used to instantiate the object