Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch between JPA and Mongo in Spring Boot MVC app

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/

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);
}

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"));
        };
    }

}

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.

like image 229
Arcane Avatar asked Oct 18 '25 14:10

Arcane


1 Answers

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;

In application.properties, you can now set spring.profiles.active to jpa or mongo to switch between databases.

like image 71
Corby Page Avatar answered Oct 20 '25 04:10

Corby Page



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!