執行上下文與解析器

MongoTemplateResolver 根據 key 選擇 MongoExecutionContext,DriverMongoExecutionContext 提供 database、session、mapping 邊界的方式。


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)
);

如果 collection 名稱在應用程序生命週期內完全固定,可以使用 DriverMongoExecutionContext.cachedCollectionNameResolver(...)。對於根據 tenant/request/time 變更名稱的 resolver,不使用快取輔助工具。

Session 範圍與交易

在 getTxJob(...) 中創建的 ClientSession 只會在同一 DSL 執行中傳播到 MongoExecutionContext#getSessionScope()。DriverMongoExecutionContext 默認使用自己的 MongoClient 作為 session 範圍。

使用 Spring Data MongoDB 的情況

© 2026 Byeolnaerim. 版權所有。介紹隱私政策