1

I have a spring service that needs to import some data into mongo given the reportKey and the report content. The issue is that the reportKey given indicates db_name/collection_name which means those 2 need to be set at runtime, when calling the restore method.

Service

@Service
class RestoreServiceImpl { 

    MongoArchiveRepository toArchiveRepository;
    
    @Autowired
    public SnapshotRestoreServiceImpl(MongoArchiveRepository toArchiveRepository) {
        this.toArchiveRepository = toArchiveRepository;
    }
    
    @Override
    public void restore(String reportKey, String reportData) {
        toArchiveRepository.save(reportData));
    }
}

MongoClient

@Configuration
@EnableMongoRepositories(basePackageClasses = MongoArchiveRepository.class)
public class MongoConfiguration {
    
    private final MongoDataStoreConfiguration mongoDbConfiguration; 
    
    @Bean
    public MongoClient mongoClient() {
        // builder returning a MongoClient instance
    }

    @Bean
    public MongoTemplate mongoTemplate(final MongoClient mongoClient) {
       return new MongoTemplate(mongoClient, "db_name");
    }
}

MongoRepository

@EnableRetry
@Repository
public interface MongoArchiveRepository extends MongoRepository<Snapshot, String> {}

and model

@Document(collection = "collection_name")
public class Snapshot implements Serializable {

    @MongoId(value = FieldType.OBJECT_ID)
    @Field("_id")
    private String id;
    
    @Field("snapshot")
    private String data;

    //setters&getters
}

The code works fine if the db name is hardcoded in the mongoTemplate and the collection name specified in the model annotation. Is there a way to set those dynamically after the restore method has been called? Any advice?

KeykoYume
  • 2,497
  • 6
  • 24
  • 48
  • If its 2 datasources, why cant you create both, including all models/repositories...and simply call the one you need when needed? – JCompetence Aug 16 '21 at 12:46
  • it's not 2, there are more than 30dbs each with hundreds of collections – KeykoYume Aug 16 '21 at 12:52
  • I think you will need to define them unfortunately. Even if lets say you create repositories, data sources, entity managers dynamically using some common code, you STILL need to define those 30 databases, their connection properties and the models themselves. – JCompetence Aug 16 '21 at 13:44
  • Might give you some possible help https://stackoverflow.com/questions/12274019/how-to-configure-mongodb-collection-name-for-a-class-in-spring-data – JCompetence Aug 16 '21 at 13:46
  • If you need to authenticate and create a connection to the database on every call to your web service, your end result will be slow and perform poorly. This is because the authentication in MongoDB is deliberately slow to prevent brute force attacks. You may want to re-think your architecture. – barrypicker Aug 16 '21 at 17:01

0 Answers0