Connect multiple database using Hibernate

Tram Ho

I. Introduction

In this article I will guide config project Spring boot connect multiple databases using hibernate, specifically here I have 2 databases: PostgreSQL and MySQL.

Here I will use kotlin.

II. Implement:

1. Maven dependencies:

Import the necessary dependencies into the project:

Next to use both Porstgresql and MySQL:

2. Config Propertiese:

Config in file application.properties, here I connect to 2 databases, MySQL and PostgreSQL

3. Config data source

Now is the config data source step in Spring, here I define 2 package repository and 2 package entities corresponding to MySQL and PostgreSQL so that jpa repository points to

Mysql:

Create a config file for MySQL MySQLConfig.kt , here I will entityManagerFactoryRef and transactionManagerRef :

Postgresql:

Similar config for postgresql, create PostgresqlConfig.kt file:

Initializer

In case you want to config when the entity has finished loading, then hibernate automatically runs sql script then config adds the Initializer as shown below:

4. Create entity package

For example, here I have 1 users_mysql table in mysql database, and I want to load all data in mysql to user_postgresql table in postgresql database

As above config, now I create the entity for mysql (package com.example.multidatabase.entity.mysql ) and postgresql (package com.example.multidatabase.entity.postgresql ):

UsersMySQLEntity.kt:

PostgreSQLEntity.kt:

5. Create repository package:

OK, had an entity, now I will create the corresponding repository mysql (package com.example.multidatabase.repository.mysql ), postgresql (package com.example.multidatabase.repository.postgresql ):

UsersMySQLRepository.kt:

UsersPostgreSQLRepository.kt:

6. Execute:

OK, now define 1 component to insert the user into MySQL and PostgreSQL every 30 seconds:

7. Result:

Log for successful start spring boot:

Log user to database:

Let’s check the database results:

Table users_postgresql :

Table users_mysql :

III. Sumary:

Thus, connecting to multiple databases with Spring boot and hibernate seems quite simple right.

Github: https://github.com/hoangntv-1399/multipledatabase

Share the news now

Source : Viblo