【问题标题】:Switch between JPA and Mongo in Spring Boot MVC app在 Spring Boot MVC 应用程序中在 JPA 和 Mongo 之间切换
【发布时间】: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


    【解决方案1】:

    你是对的,你想使用配置文件。

    @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 以在数据库之间切换。

    【讨论】:

    • 谢谢。那么我应该像你写的那样创建这些吸气剂吗?如果有,在哪里?还是应该将 Bean 和 Profile 注释放在我在原始问题中所写的接口中?
    • 您可以将 getter(带有 Bean 和 Profile 注释)放在属于 Spring Boot 组件扫描的任何类上。在上面的代码示例中,您可以将它们放在您的 Application 类中。为了清楚起见,您需要在同一类中自动装配这些私有字段(例如 @Autowired private CustomerRepositoryMongo _customerRepositoryMongo;)
    • 好的,我明白了,但只是那些吸气剂给了我一个错误'无法解析 _customerRepository。'。它不认识他们。
    • 如果它无法解析“customerRepository”,那么这意味着您没有使用关联配置文件之一(例如“jpa”或“mongo”)作为您的活动配置文件。
    猜你喜欢
    • 2016-05-17
    • 2020-12-21
    • 2023-03-16
    • 1970-01-01
    • 2018-08-17
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多