IllSc
IllSc

Reputation: 1459

Multiple database for Spring Data JPA Application with autoconfigurations

Im using Spring Data JPA over Spring Boot which give me nice autoconfiguration so I don't need to configure EntityManager and DataSource for each entities.

However, my app may need to connect to two different databases. So a few of entities on my app need to be mapped to a database , while other entities need to be mapped to a different database

I have explored this repo Link

And found out that the repo configure each EntityManager and TransactionManager for each entity. That could be very time consuming if my app has lots of entities.

Is it possible that I still rely on Spring Boot autoconfig for Spring Data JPA and still uses two different databases?

Upvotes: 3

Views: 4239

Answers (2)

manish
manish

Reputation: 20135

You only need one configuration per data source, not per entity (each data source can have multiple entities). For example, assume that you are developing a system on top of existing databases where Product Catalog is in one database, Inventory information in yet another and Order Information needs to go into a completely different database. Further, information on customers of your (new) application will need to be stored in a brand new database because owners of the other databases won't allow you to touch theirs. So, overall you have four databases to deal with.

You will need four data source configurations, one for each of the four databases you need to deal with. Each configuration must define:

  1. A SQL DataSource to provide information on connecting to the database;
  2. An EntityManagerFactory that uses the DataSource;
  3. A TransactionManager implementation that the EntityManager can use; and
  4. Reference to a Java package where the EntityManager can find the entity classes mapped to the DataSource.

If the database operations are such that they are executed against only one database at a time, you can use JpaTransactionManagers with each configuration (this means you will require four JpaTransactionManager declarations). However, if database operations may span more than one database, you can either declare a single JtaTransactionManager or declare four JpaTransactionManagers (one for each of the DataSources) and wrap them in a single ChainedTransactionManager (making a total of five transaction manager declarations).

Since your entity classes are going to be bound to a specific data source, you will need to segregate them by using different Java packages. You could for example have org.example.model.catalog, org.example.model.inventory, org.example.model.order, org.example.model.customer, etc.

Upvotes: 5

Stephane Nicoll
Stephane Nicoll

Reputation: 33151

No, and this is explained in the documentation.

This sample project shows you how you can configure things. It uses package scanning for each persistence unit.

Upvotes: 1

Related Questions