您可以扩展 MappingMongoEntityInformation 以覆盖 getCollectionName()。存储库操作对每个操作调用 getCollectionName()。我假设tenantId 将是一个 ThreadLocal
public class TenantThreadLocal extends ThreadLocal<String> {
private final static TenantThreadLocal instance = new TenantThreadLocal();
public static TenantThreadLocal instance() {
return instance;
}
}
并且省略了构造函数的重写类。
public class TenantMappingMongoEntityInformation<T, ID extends java.io.Serializable> extends MappingMongoEntityInformation<T, ID> {
@Override
public String getCollectionName() {
return TenantThreadLocal.instance().get() + super.getCollectionName();
}
}
然后创建您的存储库:
MongoPersistentEntity<YourObject> persistentEntity =
(MongoPersistentEntity<YourObject>)
mongoOperations.getConverter()
.getMappingContext()
.getPersistentEntity(YourObject.class);
MongoEntityInformation<YourObject, ObjectId> mongoEntityInformation =
new MappingMongoEntityInformation<YourObject, ObjectId>(persistentEntity);
CrudRepository<YourObject, ObjectId> repository =
new SimpleMongoRepository<YourObject, ObjectId>(mongoEntityInformation, mongoOperations);