To link two MongoDB databases in Spring Boot, you can follow these steps:
Here is an example of how to link two MongoDB databases in Spring Boot:
application.properties:
spring.data.mongodb.first.uri=mongodb://localhost/test1
spring.data.mongodb.first.database=test1
spring.data.mongodb.second.uri=mongodb://localhost/test2
spring.data.mongodb.second.database=test2
MongoConfig1.java:
@Configuration
@EnableMongoRepositories(basePackages = "com.example.demo.repository.test1",
mongoTemplateRef = "mongoTemplate1")
public class MongoConfig1 {
@Bean(name = "mongoClient1")
public MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost/test1");
}
@Bean(name = "mongoTemplate1")
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "test1");
}
}
MongoConfig2.java:
@Configuration
@EnableMongoRepositories(basePackages = "com.example.demo.repository.test2",
mongoTemplateRef = "mongoTemplate2")
public class MongoConfig2 {
@Bean(name = "mongoClient2")
public MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost/test2");
}
@Bean(name = "mongoTemplate2")
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "test2");
}
}
UserRepository.java:
@Repository
@Document(collection = "user", templateRef = "mongoTemplate1")
public interface UserRepository extends MongoRepository<User, String> {
// define your repository methods here
}
ProductRepository.java:
@Repository
@Document(collection = "product", templateRef = "mongoTemplate2")
public interface ProductRepository extends MongoRepository<Product, String> {
// define your repository methods here
}
By following these steps, you can successfully link two MongoDB databases in Spring Boot.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-03 16:58:10 +0000
Seen: 17 times
Last updated: Jun 03 '23
What are the typical approaches found in a Gradle build script?
What steps can be taken to increase the runtime of a debugger in NativeScript?
What is the method to show the dependencies in Java?
How can I incorporate BeanComparator into my gradle project?
What does the "Invalid source release 1.7" error mean when using gradle for compilation?