Configuration

您可以使用以下配置创建并注册 MongoTemplate 的实例,如下例所示:

You can use the following configuration to create and register an instance of MongoTemplate, as the following example shows:

Registering a MongoClient object and enabling Spring’s exception translation support
  • Imperative

  • Reactive

  • XML

@Configuration
class ApplicationConfiguration {

  @Bean
  MongoClient mongoClient() {
      return MongoClients.create("mongodb://localhost:27017");
  }

  @Bean
  MongoOperations mongoTemplate(MongoClient mongoClient) {
      return new MongoTemplate(mongoClient, "geospatial");
  }
}
@Configuration
class ReactiveApplicationConfiguration {

  @Bean
  MongoClient mongoClient() {
      return MongoClients.create("mongodb://localhost:27017");
  }

  @Bean
  ReactiveMongoOperations mongoTemplate(MongoClient mongoClient) {
      return new ReactiveMongoTemplate(mongoClient, "geospatial");
  }
}
<mongo:mongo-client host="localhost" port="27017" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg ref="mongoClient" />
  <constructor-arg name="databaseName" value="geospatial" />
</bean>

有几个 MongoTemplateReactiveMongoTemplate 的重载构造函数:

There are several overloaded constructors of MongoTemplate and ReactiveMongoTemplate:

  • MongoTemplate(MongoClient mongo, String databaseName): Takes the MongoClient object and the default database name to operate against.

  • MongoTemplate(MongoDatabaseFactory mongoDbFactory): Takes a MongoDbFactory object that encapsulated the MongoClient object, database name, and username and password.

  • MongoTemplate(MongoDatabaseFactory mongoDbFactory, MongoConverter mongoConverter): Adds a MongoConverter to use for mapping.

在创建 MongoTemplate/ReactiveMongoTemplate 时您可能希望设置的其他可选属性是默认 WriteResultCheckingPolicyWriteConcernReadPreference 和下面列出的其他属性。

Other optional properties that you might like to set when creating a MongoTemplate / ReactiveMongoTemplate are the default WriteResultCheckingPolicy, WriteConcern, ReadPreference and others listed below.

Default Read Preference

如果未通过 Query 定义其他首选项,则对读取操作应用的默认读取首选项。

The default read preference applied to read operations if no other preference was defined via the Query.

WriteResultChecking Policy

在开发过程中,如果任何 MongoDB 操作返回的 com.mongodb.WriteResult 中包含错误,则记录或抛出异常非常方便。在开发过程中忘记这样做很常见,然后最终得到一个看起来运行成功但实际上未按照预期修改数据库的应用程序。您可以将 MongoTemplateWriteResultChecking 属性设置为以下值之一:EXCEPTIONNONE,以分别抛出 Exception 或不执行任何操作。默认值为使用 NONE WriteResultChecking

When in development, it is handy to either log or throw an exception if the com.mongodb.WriteResult returned from any MongoDB operation contains an error. It is quite common to forget to do this during development and then end up with an application that looks like it runs successfully when, in fact, the database was not modified according to your expectations. You can set the WriteResultChecking property of MongoTemplate to one of the following values: EXCEPTION or NONE, to either throw an Exception or do nothing, respectively. The default is to use a WriteResultChecking value of NONE.

Default WriteConcern

如果尚未通过较高层级的驱动程序(例如 com.mongodb.client.MongoClient)指定,则你可以设置 MongoTemplate 在写入操作中使用的 com.mongodb.WriteConcern 属性。如果未设置 WriteConcern 属性,则会默认使用 MongoDB 驱动程序的 DB 或 Collection 设置中的属性。

If it has not yet been specified through the driver at a higher level (such as com.mongodb.client.MongoClient), you can set the com.mongodb.WriteConcern property that the MongoTemplate uses for write operations. If the WriteConcern property is not set, it defaults to the one set in the MongoDB driver’s DB or Collection setting.

WriteConcernResolver

对于希望按每个操作(移除、更新、插入和保存操作)设置不同 WriteConcern 值的更高级用例,可以在 MongoTemplate 中配置名为 WriteConcernResolver 的策略接口。由于 MongoTemplate 用于持久化 POJO,因此 WriteConcernResolver 使你可以创建可将特定 POJO 类映射到 WriteConcern 值的策略。以下清单显示了 WriteConcernResolver 接口:

For more advanced cases where you want to set different WriteConcern values on a per-operation basis (for remove, update, insert, and save operations), a strategy interface called WriteConcernResolver can be configured on MongoTemplate. Since MongoTemplate is used to persist POJOs, the WriteConcernResolver lets you create a policy that can map a specific POJO class to a WriteConcern value. The following listing shows the WriteConcernResolver interface:

public interface WriteConcernResolver {
  WriteConcern resolve(MongoAction action);
}

你可以使用 MongoAction 参数确定 WriteConcern 值,或将 Template 本身的值用作默认值。MongoAction 包含要写入的集合名称、POJO 的 java.lang.Class、转换后的 Document、操作(REMOVEUPDATEINSERTINSERT_LISTSAVE)以及其他一些上下文信息。以下示例展示了获得不同 WriteConcern 设置的两组类:

You can use the MongoAction argument to determine the WriteConcern value or use the value of the Template itself as a default. MongoAction contains the collection name being written to, the java.lang.Class of the POJO, the converted Document, the operation (REMOVE, UPDATE, INSERT, INSERT_LIST, or SAVE), and a few other pieces of contextual information. The following example shows two sets of classes getting different WriteConcern settings:

public class MyAppWriteConcernResolver implements WriteConcernResolver {

  @Override
  public WriteConcern resolve(MongoAction action) {
    if (action.getEntityType().getSimpleName().contains("Audit")) {
      return WriteConcern.ACKNOWLEDGED;
    } else if (action.getEntityType().getSimpleName().contains("Metadata")) {
      return WriteConcern.JOURNALED;
    }
    return action.getDefaultWriteConcern();
  }
}

Publish entity lifecycle events

模板发布 lifecycle events。如果不存在侦听器,则可以禁用此功能。

The template publishes lifecycle events. In case there are no listeners present, this feature can be disabled.

@Bean
MongoOperations mongoTemplate(MongoClient mongoClient) {
    MongoTemplate template = new MongoTemplate(mongoClient, "geospatial");
	template.setEntityLifecycleEventsEnabled(false);
	// ...
}

Configure EntityCallbacks

除了生命周期事件外,模板调用 EntityCallbacks,可以(非自动配置)通过模板 API 设置。

Nest to lifecycle events the template invokes EntityCallbacks which can be (if not auto configured) set via the template API.

  • Imperative

  • Reactive

@Bean
MongoOperations mongoTemplate(MongoClient mongoClient) {
    MongoTemplate template = new MongoTemplate(mongoClient, "...");
	template.setEntityCallbacks(EntityCallbacks.create(...));
	// ...
}
@Bean
ReactiveMongoOperations mongoTemplate(MongoClient mongoClient) {
    ReactiveMongoTemplate template = new ReactiveMongoTemplate(mongoClient, "...");
	template.setEntityCallbacks(ReactiveEntityCallbacks.create(...));
	// ...
}

Document count configuration

通过将 MongoTemplate#useEstimatedCount(…​) 设置为 true,当 MongoTemplate#count(…​) 操作使用空筛选查询时,它们将被委派给 estimatedCount(只要不处于活动事务状态,并且模板未绑定到 session)。有关更多信息,请参阅 Counting Documents 部分。

By setting MongoTemplate#useEstimatedCount(…​) to true MongoTemplate#count(…​) operations, that use an empty filter query, will be delegated to estimatedCount, as long as there is no transaction active and the template is not bound to a session. Please refer to to the Counting Documents section for more information.