执行上下文与解析器

MongoTemplateResolver 选择按键的 MongoExecutionContext,DriverMongoExecutionContext 提供数据库、会话、映射边界的方式。


MongoTemplateResolver 合同

MongoTemplateResolver.java
java
public interface MongoTemplateResolver<K> {
  MongoExecutionContext getTemplate(K key);
}

ReactiveMongoDsl<K>는 key마다 MongoExecutionContext를 가져옵니다. MongoExecutionContext가 MongoDatabase, ClientSession, collection naming, entity ↔ Document mapping과 save lifecycle hook의 경계를 담당합니다.

DriverMongoExecutionContext

java
MongoClient frontClient = MongoClients.create(frontConnectionString);
MongoClient backClient = MongoClients.create(backConnectionString);

MongoExecutionContext frontContext = new DriverMongoExecutionContext(
    frontClient,
    frontClient.getDatabase("front")
);

MongoExecutionContext backContext = new DriverMongoExecutionContext(
    backClient,
    backClient.getDatabase("back")
);

MongoTemplateResolver<MongoTemplateName> resolver = key ->
    key == MongoTemplateName.BACK ? backContext : frontContext;

기본 collection 이름은 entity simple class name을 decapitalize해서 결정합니다. 프로젝트의 실제 naming 규칙이 다르면 생성자에 collection-name resolver를 전달합니다.

集合命名

java
MongoExecutionContext context = new DriverMongoExecutionContext(
    mongoClient,
    mongoDatabase,
    entityClass -> collectionNameResolver(entityClass)
);

如果集合名称在应用程序生命周期内完全固定,可以使用 DriverMongoExecutionContext.cachedCollectionNameResolver(...)。对于根据 tenant/request/time 改变名称的解析器,不使用缓存助手。

会话范围与事务

在 getTxJob(...) 中创建的 ClientSession 仅在 MongoExecutionContext#getSessionScope() 中传播到相同的 DSL 执行。DriverMongoExecutionContext 默认使用自己的 MongoClient 作为会话范围。

使用 Spring Data MongoDB 时

© 2026 Byeolnaerim. 保留所有权利.介绍隐私政策