在 Spring Boot MVC 应用程序中在 JPA 和 Mongo 之间切换 [英] Switch between JPA and Mongo in Spring Boot MVC app
问题描述
我有一个用 Spring boot 编写的 Web 应用程序,它主要使用 JPA 作为数据库.我有一个简单的实体,然后我有一个存储库,它使用一些从数据库中获取数据的方法扩展 CrudRepository.基本上本教程中的所有内容 https://spring.io/guides/gs/accessing-data-jpa/
I have this web app written in Spring boot and it mainly uses JPA for database. I have a simple entity and then I have a repository that extends CrudRepository with some methods that fetch data from the database. Basically everything from this tutorial https://spring.io/guides/gs/accessing-data-jpa/
但现在我需要第二个数据库,它必须是 MongoDB.一切都与 JPA 相同,但现在我有了一个新的存储库类,这次扩展了 MongoRepository.
But now I need to have a second database and it must be MongoDB. Everything is identical to the JPA, but now I have a new repository class, that this time extends 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.在我的主要内容中,我像这样填充数据库:
So now I have two classes, CustomerRepository and CustomerRepositoryMongo. In my main I am filling the db like this:
@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 它应该使用哪个存储库.
How can I easily switch between the two dbs? I think I should maybe use profiles and select somewhere in application.properties which profile should be active, but I am new to this and I have no idea how to do it. I cannot have both interfaces with the same name and somehow I need to tell the commandLineRunner which repo should it use.
推荐答案
你说得对,你想使用配置文件.
You are correct, you want to use profiles.
@Bean( name = "customerRepository" )
@Profile( "jpa")
CrudRepository getCustomerRepository()
{
return _customerRepository;
}
@Bean( name = "customerRepository" )
@Profile( "mongo")
MongoRepository getCustomerRepositoryMongo()
{
return _customerRepositoryMongo;
}
@Autowired
@Qualifier("customerRepository")
CrudRepository _crudRepository;
在 application.properties 中,您现在可以将 spring.profiles.active 设置为 jpa 或 mongo 以在数据库之间切换.
In application.properties, you can now set spring.profiles.active to jpa or mongo to switch between databases.
这篇关于在 Spring Boot MVC 应用程序中在 JPA 和 Mongo 之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!