How to select dinamically a mongo database(multitenant)

时间:2017-11-08 22:07:54

标签: javers

I created a bean with Scope(value=prototype) and works fine for repositories with the @JaversSpringDataAuditable annotation. All data is saved in the appropiate database.

 @Bean
 @Scope(value = "prototype")
 @Lazy(value = true)
 public Javers javers() {

     Authentication auth =  SecurityContextHolder.getContext().getAuthentication()
     String tenantId = null

     if (auth == null) {
         tenantId = "unauthenticated"
     }else{
         tenantId = auth.getName().toString()
     }

     System.out.println("Selected " + tenantId.toString())

     MongoRepository javersMongoRepository =
             new MongoRepository(mongo().getDatabase(tenantId));

     return JaversBuilder.javers()
             .registerJaversRepository(javersMongoRepository)
             .build();
 }

In one specific class I need more fine-grained control over Javers commit. When I call a manual commit, always return me "unauthenticated"

This code always save the data in a database called "unauthenticated"

@Autowired
Javers javers
def saveDTO(AuthUtils authUtils, DTO dto){
  javers.commit(authUtils.currentUser.email, dto)
}

Any help will be appreciable. Thanks.

1 个答案:

答案 0 :(得分:0)

目前,您必须将具体的MongoDatabase传递给JaVers实例,并且无法在运行时更改此实例。对于您的(多租户)情况,MongoRepository API应该以这种方式工作:

MongoDatabaseProvider dbProvider = new MongoDatabaseProvider() {
    public MongoDatabase provide() {
        SecurityContextHolder.getContext().getAuthentication()
        ... your code
    }
}

MongoRepository javersMongoRepository =
             new MongoRepository(dbProvider);
}

在JaVers中实现此API很容易。如果您愿意,我们将接受PR。