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:

  • 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.

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

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

  • 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