How to Connect Two Databases in One Spring Boot Application (MySQL + Oracle Example)



How to Connect Two Databases in One Spring Boot Application (MySQL + Oracle Example)

In modern microservices and enterprise systems, it’s not uncommon to work with more than one database. You may have one system using MySQL and another using Oracle or PostgreSQL, and your Spring Boot application must interact with both.

In this guide, you’ll learn how to configure two databases in a single Spring Boot application, step by step, with an example using MySQL and Oracle.

Why Use Multiple Databases?

Here are some common use cases:

  • You’re integrating with a legacy system on Oracle while using a new module on MySQL.

  • Your microservice reads from one DB and writes to another.

  • You are performing data migration between two systems.

Tools & Technologies Used

  • Java 17+ (or Java 8+)

  • Spring Boot 3.x

  • Spring Data JPA

  • MySQL and Oracle drivers

  • Maven

Step-by-Step: Configuring Two Databases in Spring Boot

Step 1: Add Required Dependencies

Add the following to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>19.3.0.0</version>
</dependency>

Step 2: Configure Application Properties

Update application.yml to include both DB configs.

spring:
  datasource:
    mysql:
      url: jdbc:mysql://localhost:3306/db1
      username: user1
      password: pass1
      driver-class-name: com.mysql.cj.jdbc.Driver

    oracle:
      url: jdbc:oracle:thin:@localhost:1521:xe
      username: user2
      password: pass2
      driver-class-name: oracle.jdbc.OracleDriver

Step 3: Create MySQL Configuration Class

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackages = "com.example.mysql.repo",
    entityManagerFactoryRef = "mysqlEntityManagerFactory",
    transactionManagerRef = "mysqlTransactionManager"
)
public class MySQLConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(
            EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(mysqlDataSource())
                .packages("com.example.mysql.model")
                .persistenceUnit("mysqlPU")
                .build();
    }

    @Bean
    @Primary
    public PlatformTransactionManager mysqlTransactionManager(
            @Qualifier("mysqlEntityManagerFactory") EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }
}

Step 4: Create Oracle Configuration Class

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackages = "com.example.oracle.repo",
    entityManagerFactoryRef = "oracleEntityManagerFactory",
    transactionManagerRef = "oracleTransactionManager"
)
public class OracleConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.oracle")
    public DataSource oracleDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory(
            EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(oracleDataSource())
                .packages("com.example.oracle.model")
                .persistenceUnit("oraclePU")
                .build();
    }

    @Bean
    public PlatformTransactionManager oracleTransactionManager(
            @Qualifier("oracleEntityManagerFactory") EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }
}

Step 5: Organize Your Package Structure

Structure your code like this:

com.example
├── mysql
│   ├── model
│   └── repo
└── oracle
    ├── model
    └── repo

Ensure the @Entity classes are placed in the correct folders and use the correct package path in .packages() in the config classes.

Step 6: Using Both Databases in Service

@Service
public class DualDBService {

    @Autowired
    private com.example.mysql.repo.UserRepository userRepo;

    @Autowired
    private com.example.oracle.repo.ProductRepository productRepo;

    public void process() {
        List<User> users = userRepo.findAll();
        List<Product> products = productRepo.findAll();
    }
}

🧪 Test and Verify

Once the application is running, test the endpoints or services to verify both DBs are working. You can also enable Spring Actuator to monitor DB health via /actuator/health.

SEO Keywords Used

  • How to connect two databases in Spring Boot

  • Spring Boot multiple database configuration

  • Spring Boot MySQL and Oracle integration

  • Spring Data JPA with multiple datasources

  • Configure two datasources in Spring Boot application

Conclusion

Connecting multiple databases in a single Spring Boot application may seem tricky at first, but it’s a common enterprise pattern. With the right configurations for each DataSource, EntityManager, and TransactionManager, Spring Boot handles it gracefully.

Comments