Multiple Databases with shared entity classes in Spring Boot and Java.

Hello everyone, It has been a few months since my last post. I have been busy travelling and relocating . In this post I want to illustrate how a Spring Boot application can have multiple data sources with shared entity classes. The need for this arose in my current project where an in-memory database was needed for the high performance and a persistent database for storage.

In this blog post, I will use H2 for the in-memory database and Postgres for the persistent storage. I will setup up the application and show how the entities can be passed from one data source to another.

The application will be a Spring Boot application using Java 8 with REST enabled.  I will highlight the important parts and classes of the application. The link to the Github code is given below.

The application will save a Person entity to an in-memory database and to a persistent database via a REST POST call. We create our entity,


For the sake of brevity I leave out the Getters and Setters.

Next we setup the two connections for the two databases. I will leave out the reading of the properties but highlight the important parts of the classes, and



As you can see from the two classes the same data model package is used com.gabriel.multipledatabaseconnection.model. This means that the two databases will share the same Entities and within the application they can be passed to and fro between the data sources.

Next we configure our respositories. These are very simple and just extend Spring’s JpaRepository:



The last step is to setup a controller which I call the MutlipleDatabaseController. We will create a new person in both databases but simple passing the new person entity from the in-memory database to the persistent database:


Note that the transaction managers are defined for the respective data sources and annotate the respective methods.

Last we test. For this I will use SoapUI the opensource version, To make a REST call to create John Connor:


If we check in our databases using pgAdmin4 and H2 web console:



There you have it, one REST call two data sources one entity persisted in both. The Github link is Note have also added the .idea files if using Intellij( This is for the open source version of Intellij).




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s