Collection based multi tenancy in spring data mongo

喜你入骨 提交于 2019-12-04 20:02:57

You could extend MappingMongoEntityInformation to override getCollectionName(). The repository operations call getCollectionName() on each operation. I'm assuming the tenantId would be a ThreadLocal

public class TenantThreadLocal extends ThreadLocal<String> {
    private final static TenantThreadLocal instance = new TenantThreadLocal();

    public static TenantThreadLocal instance() {
        return instance;
    }
}

And the overridden class with the constructors omitted.

public class TenantMappingMongoEntityInformation<T, ID extends java.io.Serializable>  extends MappingMongoEntityInformation<T, ID> {

    @Override
    public String getCollectionName() {
        return TenantThreadLocal.instance().get() + super.getCollectionName();
    }
}

Then create your repository:

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!