I have to access two databases from the Same Cluster. Actually, I’m working with a single database at the moment. I have to access another database from the same cluster in order to perform more aggregation queries for my application. Are there any way to achieve that in Spring Boot
You have the answer in my Java Spring Boot MongoDB Starter repository in Github.
In this starter pack, I create the MongoClient
bean like this in SpringConfiguration.java
:
@Bean
public MongoClient mongoClient() {
CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
return MongoClients.create(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString))
.codecRegistry(codecRegistry)
.build());
Then in the MongoDBPersonRepository.java
, I inject that bean and initialises the access to my database and collection during the init of this bean using a @PostConstruct
. Nothing prevents you from initialising more MongoCollection at this point, using a different DB or not.
@Repository
public class MongoDBPersonRepository implements PersonRepository {
private final MongoClient client;
private MongoCollection<Person> personCollection;
public MongoDBPersonRepository(MongoClient mongoClient) {
this.client = mongoClient;
}
@PostConstruct
void init() {
personCollection = client.getDatabase("test").getCollection("persons", Person.class);
}
}
That’s not the only way to do it. But I feel like this is a clean solution.
Cheers,
Maxime.
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.