【发布时间】:2016-09-26 21:44:46
【问题描述】:
我有这个用 Spring Boot 编写的 Web 应用程序,它主要使用 JPA 作为数据库。我有一个简单的实体,然后我有一个存储库,它使用一些从数据库中获取数据的方法来扩展 CrudRepository。基本上本教程的所有内容https://spring.io/guides/gs/accessing-data-jpa/
但现在我需要第二个数据库,它必须是 MongoDB。一切都与 JPA 相同,但现在我有一个新的存储库类,这次扩展了 MongoRepository。
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
public interface CustomerRepositoryMongo extends MongoRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
所以现在我有两个类,CustomerRepository 和 CustomerRepositoryMongo。在我的主要内容中,我正在像这样填充数据库:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args) -> {
// save a couple of customers
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
};
}
}
如何在两个数据库之间轻松切换?我想我可能应该使用配置文件并在 application.properties 中选择哪个配置文件应该处于活动状态,但我对此并不陌生,我不知道该怎么做。我不能同时拥有同名的两个接口,并且不知何故我需要告诉 commandLineRunner 它应该使用哪个 repo。
【问题讨论】:
标签: java spring mongodb spring-boot spring-data